RSS

Quick Sort in C#

21 Aug

A simple Quick Sort implementation using C#. In this version the pivot is the last element in every sub array.

public static void QuickSort(int[] input, int left, int right)
{
    if (left < right)
    {
        int q = Partition(input, left, right);
        QuickSort(input, left, q - 1);
        QuickSort(input, q + 1, right);
    }
}

private static int Partition(int[] input, int left, int right)
{
    int pivot = input[right];
    int temp;

    int i = left;
    for (int j = left; j < right; j++)
    {
        if (input[j] <= pivot)
        {
            temp = input[j];
            input[j] = input[i];
            input[i] = temp;
            i++;
        }
    }

    input[right] = input[i];
    input[i] = pivot;

    return i;
}
Advertisements
 
3 Comments

Posted by on August 21, 2012 in Algorithm, C#

 

3 responses to “Quick Sort in C#

  1. Jonathan

    April 9, 2014 at 3:00 AM

    Thank you!

     
  2. anonym

    March 1, 2016 at 4:47 PM

    what should left and right by calling method be?

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: