-
integer sort fix
This sort program is not working correctly, I was wondering what was wrong:
#include <iostream.h>
#include <stdlib.h>
int main()
{
int num[6];
int temp;
cout << "Enter 5 numbers to be sorted: ";
cin >> num[0] >> num[1] >> num[2] >> num[3] >> num[4];
for(int i=0; i<6; i++){
if(num[i] >= num[i+1]){
temp = num[i+1];
num[i+1] = num[i];
num[i] = temp;
}
}
for(int j=0; j<5; j++){
cout << num[j] << " ";
}
}
It sorts it somewhat, but it is not in the correct order(least to greatest). Thanks for the help.
-
you are only looping through the array once so each element will only have had one comparison.... you need to add another loop around the outside of the first loop to keep looping all through the array until its sorted. if an array has x elements then this loop needs to run x-1 times!
-
This sort program is not working correctly, I was wondering what was wrong:
#include <iostream.h>
#include <stdlib.h>
int main()
{
int num[6];
int temp;
cout << "Enter 5 numbers to be sorted: ";
cin >> num[0] >> num[1] >> num[2] >> num[3] >> num[4];
...for(int i=0; i<5; i++){ //changed 6 to 5
......for(int k=i+1;k<6;k++) //added inner loop
......{
..........if(num[i] > num[k]){ //removed = why swap on = ??
//that is like giving you a dollar in return for a dollar
//to change the asceding or descending change
//the comparison symbol from > to <
.............temp = num[k];
.............num[k] = num[i];
.............num[i] = temp;
..........}
.......}
..}
...for(int j=0; j<5; j++){
......cout << num[j] << " ";
....}
...}
zMan -- :-) Have a nice day