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
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
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
will get incremented beyond the end of your nums
array. Try modifying the while condition thus:
while ((i<nums.Length) && (nums[i]<pivot))
Of course you could simply use Array.Sort(nums);
精彩评论