Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C#
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;
    }
Posted
Updated 19-Dec-10 4:16am
v3

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"
 
Share this answer
 
Hi Arash,

the line that reads int temp = i;
should most probably read like int 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
 
Share this answer
 
v2
Comments
arashmobileboy 19-Dec-10 10:23am    
wow,it solved,thanks so much
Manfred Rudolf Bihy 19-Dec-10 10:54am    
You're welcome! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900