C#中的QuickSort算法问题 [英] Problem with QuickSort algorithm in C#
问题描述
朋友,我用c#编写了一个快速排序算法,但是有一个问题,当我编译它时,它在某些情况下不起作用.例如,当我在textbox6中输入数字12、32、11进行排序时,它给出了超出范围的错误.当我去追踪它时,调试器显示num []取了nums [0] = 12,nums [1] = 11,nums [2] = 1我在问题中做了评论,在此先感谢
已编辑:我更改了while条件,但现在不会出现超出范围的错误,但是当输入为12,32,11时输出11,12,1
Hi friends, I wrote a quicksort algorithm in c# but it has a problem,when I compile it, it doesn''t work in some conditions. For example when I enter number 12, 32, 11 in textbox6 to sort, it gives out of range error. When I go to trace it, debugger shows that num[] took nums[0]=12, nums[1]=11, nums[2]=1 I commented in the lines of problem, thanks in advance
Edited: I changed the while condition and it now doesn''t give out of range error but when the input is 12,32,11 output 11,12,1
private void button5_Click(object sender, EventArgs e)
{
string[] x = textBox6.Text.Split(',');
int[] nums = new int[x.Length];
for (int counter = 0; counter < x.Length; counter++)
{
nums[counter] = Convert.ToInt32(x[counter]);
}
int i = 0;
int j = nums.Length;
int pivot = nums[0];
do
{
do
{
i++;
}
while ((i < nums.Length) && (nums[i] < pivot));
do
{
j--;
}
while (nums[j]>pivot);
if (i < j)
{
int temp = i;
nums[i] = nums[j];
nums[j] = temp;
}
}while(i<j);
int temp1 = nums[0];
nums[0] = nums[j];
nums[j] = temp1;
int pivotpoint = j;
string QuickSort = "";
foreach (var n in nums)
QuickSort += n.ToString() + ",";
textBox5.Text = QuickSort;
}
推荐答案
是的,它会的.
因为您要在循环保护中检查的全部是"nums [i] <pivot",如果第一个元素在组中最大,则循环将总是用完元素.您必须选中"i< nums.Length"或"i< j"
Yes, it will do.
Because all you check for in the loop guard is "nums[i] < pivot" if the first element is the largest in the group the loop will always run out of elements. You must include a check for "i < nums.Length" or "i < j"
阿鲁什,
读取int temp = i;
的行 应该最可能读为int temp = num[i];
因为i和j是索引,而您要使用
完成 名为temp的变量是将数组元素num [i]与num [j]交换.
这就是我在您的代码中看到的问题.
问候,
曼弗雷德(Manfred)
Hi Arash,
the line that readsint temp = i;
should most probably read likeint temp = num[i];
because i and j are indexes and what you''re trying to accomplish with
the variable named temp is swapping of the array element num[i] with num[j].
That''s the problem I see with your code.
Regards,
Manfred
这篇关于C#中的QuickSort算法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!