[英]Problem with QuickSort algorithm in C#
i wrote i quicksort algorithm in c# but it has a problem,when i compile it,it doesnt 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 我在C#中编写了quicksort算法,但有一个问题,当我对其进行编译时,它在某些情况下不起作用,例如,当我在textbox6中输入数字12,32,11进行排序时,当我转到追踪它,调试器显示num []取nums [0] = 12,nums [1] = 11,nums [2] = 1
Edited: i changed the while condition and it know doesnt give out of range error but when the input is 12,32,11 output 11,12,1 编辑:我改变了while条件,它知道不会超出范围错误,但当输入是12,32,11输出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;
}
Your issue is that i
isn't being bounds-checked in your do-while loop. 你的问题是
i
没有在你的do-while循环中进行边界检查。 i
will get incremented beyond the end of your nums
array. i
将在你的nums
数组的末尾增加。 Try modifying the while condition thus: 尝试这样修改while条件:
while ((i<nums.Length) && (nums[i]<pivot))
Of course you could simply use Array.Sort(nums);
当然你可以简单地使用
Array.Sort(nums);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.