所以我刚开始学习C和算法,我在选择排序算法中遇到了一个问题。它给了我这个输出:
>10
>12
>13
>16
>23
>25
>42
>60
>50
>52
最后三位数字无序。从我的眼睛看,他们不应该。你能告诉我们这里有什么问题吗?另外我的目标是在没有任何指示的情况下这样做,从上一次演讲开始它仍然有点模糊,我知道没有它就可以完成。我相信这更符合逻辑而不是内存错误。谢谢大家!
#include <stdio.h>
int main(void) {
int max = 10;
int a[max];
//Makes unsorted array
a[0] = 10;
a[1] = 23;
a[2] = 50;
a[3] = 12;
a[4] = 52;
a[5] = 60;
a[6] = 25;
a[7] = 13;
a[8] = 42;
a[9] = 16;
/*
SWAP MODEL
printf("a[2] = %d \n", a[2]);
int temp = a[3];
a[3] = a[2];
a[2] = temp;
printf("a[2] = %d \n", a[2]);
*/
//Sorts array
int n;
int s = 0;
int p = 0;
for (n = 0; n < max-1; n++){
int smallest = a[n];
for(s = n + 1; s < max; s++){
if(smallest > a[s]) {
smallest = a[s];
p = s;
}
}
if (n == 0 && p == 0) {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else if (n > 0 && p == 0) {
p = n;
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
}
//Checks if sorted
for(int number = 0; number < 10; number++) {
printf("%d \n", a[number]);
}
}
答案 0 :(得分:3)
int smallest = a[n];
此处您忘记初始化p = n
,因此违反了您的不变smallest == a[p]
。有了它,它就可以了。
更多评论:
if (n == 0 && p == 0) {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else if (n > 0 && p == 0) {
p = n;
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
else {
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}
这整个构造是多余的,它在每种情况下都做同样的事情。您可以通过无条件交换替换它。我尝试清理版本:
for (int n = 0; n < max-1; n++){
int p = n;
int smallest = a[p];
for (int s = n + 1; s < max; s++){
if (smallest > a[s]) {
smallest = a[s];
p = s;
}
}
int temp = a[n];
a[n] = a[p];
a[p] = temp;
}