【发布时间】:2021-04-08 18:03:56
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;
srand(time(&t));
for (ctr = 0; ctr < 10; ctr++) {
nums[ctr] = (rand() % 99) + 1;
}
printf("\nHere is the list before the sort:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
// Sorting the array
for (outer = 0; outer < 9; outer++) {
didSwap = 0;
for (inner = outer + 1; inner < 10; inner++) {
if (nums[inner] < nums[outer]) {
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
}
if (didSwap == 0) {
break;
}
}
printf("\n\nHere is the list after sorting:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
printf("\n");
return 0;
}
它在大多数情况下都能正常工作,但有时无法正确排序,有时根本无法排序。
附:如果代码不正确,那么为什么它在 85% 的情况下都能正常工作。
【问题讨论】:
-
找到一个不起作用的特定情况,尝试最小化输入集,然后使用调试器在监视变量和语句的同时逐语句执行代码他们的价值观。
-
这是相同的code you posted 2 days ago。这个问题有什么不同?
-
@Blastfurnace 啊是的你是对的
-
希望我的回答能回答您关于有时不排序的问题,但无论如何,像您那样复制问题不是正确的方法。请选择具有您喜欢的答案的问题并删除另一个问题,如果您不尽快,我们会这样做并且可能不是您喜欢的方式,包括删除您的两个问题...
标签: c sorting selection-sort