简体   繁体   中英

confused with Quick sort algorithm C#

I've been working out how to do quicksort in C# for college. I've nearly got it working.Only a few numbers don't appear in the correct order. array: 1,5,8,6,7,3,2,4,9 "sorted" into: 1,5,4,6,2,3,7,8,9 instead of 1,2,3,4,5,6,7,8,9. Not sure where I'm going wrong in my code:

int[] array4 = { 1, 5, 8, 6, 7, 3, 2, 4, 9};
QuickSort quick = new QuickSort();
quick.Quicksort(array4, 0, array4.Length - 1);

public void Quicksort(int[] array, int left, int right)
{
        int pivot, temp;                      
        pivot = array[(left + right / 2)];
        do
        {
            while ((array[left] < pivot) && (left < right))
                left++;

            while ((pivot < array[right]) && (right > left))
                right--;
            if (left <= right)
            {
                temp = array[left];
                array[left] = array[right];
                array[right] = temp;
                left++;
                right--;
            }
        }
        while (left <= right);

        if (left < right) Quicksort(array, left, right);              
        }            
 }

Thanks

In your Quicksort method, as Lee's comment points out, you are not calling the quicksort method with the left and right portions of the partition/pivot.

First I am confident you are not getting the proper pivot at the line:

pivot = array[(left + right / 2)];

Above, the division will happen first, so it will divide “right” by two then add to “left”. This is going to give you the wrong pivot. It should be:

pivot = array[(left + right) / 2];

Second, when you enter the Quicksort method, you are given the STARTING index values (left/right) and you use these variables to get the next pivot. This will throw off the “left” and “right” STARTING indexes when you change them. So you need to make a copy of those STARTING values and use the copied values to create the next partition/pivot.

Below are changes I made to your code and it appears to work properly.

public static void Quicksort(int[] array, int left, int right)
{
  int pivot, temp;
  pivot = array[(left + right) / 2];
  int originalLeft = left;
  int originalRight = right;
  do
  {
    while (array[left] < pivot)
      left++;

    while (pivot < array[right])
      right--;
    if (left <= right)
    {
      temp = array[left];
      array[left] = array[right];
      array[right] = temp;
      left++;
      right--;
    }
  }
  while (left <= right);

  // note that the original left and right values are needed here
  if (originalLeft < right)
    Quicksort(array, originalLeft, right);
  if (left < originalRight)
    Quicksort(array, left, originalRight);
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM