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 for
loop i<=count
is incorrect.
Valid index in the array are 0
to count-1
.
Since you are accessing value at index i+1
in the loop:
if (numbers[i] > numbers[i+1])
i
can take the value from 0
to count-2
, so change the condition to i<=count-2
or i<count-1
You are trying to implement the bubble sort algorithm. Read this to understand what your code is missing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With