我知道 C# 中有一个排序函数可以将数组排序为正确的顺序,但由于某些原因,我需要用自己的代码来完成。
我想出了这个,一些数字移动了,但它从未完全排序。有人知道为什么吗?
static void Main(string[] args)
{
int[] arraySort = { 2, 5, 7, 3, 6, 3 };
int save;
bool sorted = false;
while(sorted == false) {
for (int i = 0; i < (arraySort.Length - 1); i++)
{
sorted = true;
if (arraySort[i] > arraySort[i + 1])
{
save = arraySort[i];
arraySort[i] = arraySort[i + 1];
arraySort[i + 1] = save;
sorted = false;
}
}
}
for (int i = 0; i < arraySort.Length; i++)
{
Console.WriteLine(arraySort[i]);
}
}
我的输出最终是:
2 3 5 3 6 7
最佳答案
您在 for 循环内设置 sorted = true
。
因此,只要倒数第二个条目小于最后一个条目,它就会停止。验证外循环时忽略所有其他检查
关于c# - 为什么这个程序不对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32849021/