I have a functions, which takes an Array of numbers, and sort them from low to high. So far, I have this algorithm, however the output isn’t what I’m expecting. Can someone shed some light on it. I cannot use any C library functions.
/*
Sort "count" numbers stored in array numbers[] in non-decreasing order.
There may be duplicate numbers in the array.
You may use any sorting algorithm that you know.
*/
void sort( double numbers[], int count )
{
int i, j, k;
//printf("%d", count);
double temp;
do{
j = 0;
for (i = 0;i<=count;i++){
if (numbers[i] > numbers[i+1]){//this was numbers[k], which was an error
j = 1;
temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
}
}
} while (j == 1);
}
The condition in
forloopi<=countis incorrect.Valid index in the array are
0tocount-1.Since you are accessing value at index
i+1in the loop:ican take the value from0tocount-2, so change the condition toi<=count-2ori<count-1