[英]Why does this sorting doesn't work ? (C)
I am trying to create a sorting method based on selection sort algorithm With this current code, the array [10, 9, 8 .. 1] is "sorted" to [9, 8 .. 2, 10, 1] I mean like, it doesn't even put 10 in the right place我正在尝试创建基于选择排序算法的排序方法使用当前代码,数组 [10, 9, 8 .. 1] 被“排序”为 [9, 8 .. 2, 10, 1] 我的意思是像,它甚至没有把 10 放在正确的位置
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
"sorted" to “排序”到
9 8 7 6 5 4 3 2 10 1
9 8 7 6 5 4 3 2 10 1
What's the problem ?有什么问题 ?
void selectionSort(int array[], int length)
{
int i = 0, j = 0, temp = 0, swap = 0;
for(i = 0; i < length; i++)
{
temp = i;
for(j = 0; j < length; j++)
{
if(array[temp] > array[j])
{
temp = j;
}
}
swap = array[temp];
array[temp] = array[i];
array[i] = swap;
}
}
The inner loop should be written like内循环应该写成
for(j = i + 1; j < length; j++)
^^^^^^^^^
After each iteration of i, the array upto i , should be sorted.在 i 的每次迭代之后,应该对直到 i 的数组进行排序。 You can print the array after each iteration of i and can see the logical error.
您可以在 i 的每次迭代后打印数组,并可以看到逻辑错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.