### Array Sorting (2.3040923)

Im having problem with the fact that its not sorting the first number of the array into order? Also can you tell me what type of sort im using?

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445`` ``````#include #include using namespace std; int main() {//array test int heights[10]; for(int i=0; i<10; ++i) { cout << "\nEnter height for student " << i+1<<" "; cin >> heights[i]; } for(int i=0;i<10;i++) { cout <<"\nHeight for student number "<0 && heights[i] > key) {heights[i+1]=heights[i]; i=i-1;} heights[i+1] = key; } system("PAUSE"); for(int x=0;x<10;x++) { cout <<"\n"<< heights[x]; } system("PAUSE"); return 0 ; }``````
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657`` ``````#include #include using namespace std; int main() { //array test int heights[10]; for(int i=0; i < 10; ++i) { cout << "\nEnter height for student " << i+1<<" "; cin >> heights[i]; } for(int i = 0;i < 10; i++) { cout <<"\nHeight for student number "<< i + 1 << " is " << heights[i] <<"cm" << endl;; } //Selection sort int temp; int i, j; int smallest; int size = 10; for (i = 0; i < size - 1; i++) { smallest = i; for (j = i + 1; j < size; j++) { if( heights[j] < heights[smallest] ) { smallest = j; } } //swap temp = heights[smallest]; heights[smallest] = heights[i]; heights[i] = temp; } // To see sorted array for(int i = 0; i < 10; i++) { cout << heights[i] << " " ; } system("PAUSE"); return 0 ; }``````

Does this work better?
I used a high number like 58 for the first one. Then all the other values were lower and it seemed that it sorted it correctly. This is selection sort. I believe. I wrote it below with the variables above it . You should just make it a function it would be more appropriate I think. Well let me know if that is what you wanted.
thank you but I wanted to know why mine didn't work and what kind of sorting I used? . Ofcourse your one does work and thanks for your time
Line 35 `heights[i+1] = key;`
The value `key` will be placed into the lowest element of the array when i+1 == 0. In order for that to be true, i must be equal to -1.

That cannot currently happen. The while loop at line 32 ends when i equals 0.
Solution, change line 32 to `while (i>=0 && heights[i] > key)`
Last edited on
Topic archived. No new replies allowed.