最近我被要求制作一个数组排序器,但是已经有内置函数,但是我不需要它,我想知道为什么以下脚本在它通过时不会继续评论行?
int n;
int t = 0;
Console.Write("How many elements do you want to add? ");
int length = Convert.ToInt32(Console.ReadLine());
int[] List = new int[length];
while (t < length)
{
Console.Write("Enter {0} element value: ", t);
n = Convert.ToInt32(Console.ReadLine());
List[t] = n;
++t;
}
/////V The Below code is skipped for some reason V\\\\\
int temp;
int min = List[1];
int min_i = 1;
if (length < 2) { Console.WriteLine("Sorry, You can't sort a short list!"); }
else
{
for (int y = 1; y > length;)
{
for (int x = min_i - 1; x < 0; x--)
{
if (List[min_i] < List[x])
{
temp = min;
List[min_i] = List[x];
List[x] = temp;
}
else break;
}
y++;
min = List[y];
min_i = y;
}
}
for(int z = 0; z > length; z++)
{
Console.Write(List[z] + " ");
}
答案 0 :(得分:1)
忽略其余部分(并添加到其他人评论的内容) - 此循环将始终为false:
for (int y = 1; y > length;) // y = 1; length >= 2
答案 1 :(得分:0)
为for
循环定义的条件总是 false。
for (int x = min_i - 1; x < 0; x--) // x is zero and condition is false.
我想,你必须将上面一行更改为
for (int x = min_i - 1; x > 0; x--)
与顶级循环类似的情况,您可能需要查找y<length
答案 2 :(得分:0)
int n;
int t = 0;
Console.Write("How many elements do you want to add? ");
int length = Convert.ToInt32(Console.ReadLine());
int[] List = new int[length];
while (t < length)
{
Console.Write("Enter {0} element value: ", t);
n = Convert.ToInt32(Console.ReadLine());
List[t] = n;
++t;
}
/////V The Below code is skipped for some reason V\\\\\
int temp;
int min = List[1];
int min_i = 1;
if (length < 2) { Console.WriteLine("Sorry, You can't sort a short list!"); }
else
{
for (int y = 1; y <= length - 1; y++) //see #1 and #2
{
for (int x = min_i - 1; x >= 0; x--) //for loop was backwards see #2
{
if (List[min_i] < List[x])
{
temp = min;
List[min_i] = List[x];
List[x] = temp;
}
else break;
}
//remove y++; and added to for loop
min = List[y];
min_i = y - 1;
}
}
for (int z = 0; z <= length - 1; z++) //see #1 and #2
{
Console.Write(List[z] + " ");
}
Console.Read(); //added to prevent the program from closing until you press enter or manually close it
好吧,所以你排序代码并不起作用。仍然需要解决一些问题。就你的代码而言.......
1)所以数组从0开始而不是1.你的长度不是。由于长度为4,代码断开,但数组只到3([0],[1],[2],[3])所以通过添加&#34; length - 1&#34;,你不会改变长度,但你仍然可以使用与数组相同的数字来引用它,并且它不会超出数组。
2)你几乎所有的陈述都是向后发的。让我看看我是否可以帮助你更好地记住它。
for(int a = 0;
这部分只是初始化值
a&lt; = 10;
将此视为一种时间陈述。而(a&lt; = 10){继续运行for循环}
一++)
当然还有增量。
如果您愿意,我可以帮助您完成排序算法,因为我在学校时必须做类似的项目,因为现在它不像它一样工作应该。干杯!