0

why this code does not work? it does not show me output

#include <stdlib.h> #include <iostream> #include <string.h> void Sort(int *arr,int length){ int *iter=arr; char buf[12],buf1[12]; while ((iter++)< (arr+length)){ if (iter==arr || (strcmp(itoa(*iter,buf,10),itoa(*(iter-1),buf1,10))>=0)){ iter++; } else{ *iter^=*(iter+1); *(iter+1)^=*iter; *iter^=*(iter+1); iter--; } } } int main(){ int a[]={1,2,10,100,19,21,2,4,31}; int n=sizeof(a)/sizeof(int); Sort(a,n); for(int i=0;i<n;i++) std::cout<<a[i]<<" "; return 0; } 

please help

6
  • are you sure it's finishing sorting? Commented Oct 27, 2010 at 7:13
  • Don't write your own sort routine; write a comparator, and leverage the STL. Commented Oct 27, 2010 at 7:22
  • 2
    "Does not work" is not an error description. tinyurl.com/so-hints Commented Oct 27, 2010 at 7:24
  • What are you expecting from this line? strcmp(itoa(*iter,buf,10),itoa(*(iter-1),buf1,10) Commented Oct 27, 2010 at 7:35
  • 1
    Don't use such weird swap routines. std::swap(*iter, *(iter+1)); is a lot shorter and a lot clearer. Commented Oct 27, 2010 at 8:26

1 Answer 1

3

Here is the output using gcc 4.5.1:

> g++ -o test test.cpp > test.exe 1 2 10 100 19 21 2 4 31 

As you can see, it compiles and runs fine in my place. Whether it works like intended is another matter though.

Are you sure you saved your changes before compiling ? What compiler are you using ?


Moreover, you should better use a std::vector to store the integers and std::sort with a custom comparator object to do the sort.

Sign up to request clarification or add additional context in comments.

3 Comments

The expected output is 1 10 100 19 2 2 31 4. Sorting by digit.
@Manoj R: Sure. But the OP states that his example does not output anything at all. So I guess his first problem is to solve this before.
You don't need a custom comparator. Just use a std::vector<std::string>, and sort that. I.e. move the int-to-string conversion before the sort phase.