smo*_*hie 4 c arrays sorting algorithm
我有一个函数,它接受一个数字数组,并从低到高排序.到目前为止,我有这个算法,但输出不是我所期望的.有人可以对此有所了解.我不能使用任何C库函数.
/*
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);
}
Run Code Online (Sandbox Code Playgroud)
for循环中的条件i<=count不正确.
阵列中有效的索引是0对count-1.
由于您i+1在循环中访问索引值:
if (numbers[i] > numbers[i+1])
Run Code Online (Sandbox Code Playgroud)
i可以从取的值0到count-2,所以改变条件 i<=count-2或i<count-1
| 归档时间: |
|
| 查看次数: |
33958 次 |
| 最近记录: |