#include <iostream>
#include <string>
usingnamespace 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.
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)