I have a functions, which takes an Array开发者_JAVA技巧 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.
The value of k
is used, but the variable is never initialized or assigned to. At some point your code will try to access the value numbers[count]
, when an array containing count
elements has maximum index count-1
You haven't initalised k
.
The algorithm will stop as soon as it has moved just one number. You need to move all of them.
I think you are missing a for loop on k
outside the while loop, but as I'm not entirely sure what you're trying to do here I can't be sure.
Why can't you implement your own qsort() function? Is that allowed? Try reading up on a few sorting algorithms online.
if (numbers[i] > numbers[k]){
should probably be
if (numbers[i] > numbers[i+1]){
k
isn't used at all.
for (i = 0;i <= count;i++){
should probably be
for (i = 0; i < count-1;i++){
as there are only elements from 0 to count-1, and then you are comparing to the next one.
The name for j
is crap. Make it a boolean called didSwap. And then rethink about your codition, maybe it's just the other way around...
精彩评论