Quick Sort Algorithm C#

11 12 2007

The quick sort is an in-place, divide-and-conquer, massively recursive sort. As a normal person would say, it’s essentially a faster in-place version of the merge sort. The quick sort algorithm is simple in theory, but very difficult to put into code.

The recursive algorithm consists of four steps:

  1. If there are one or less elements in the array to be sorted, return immediately.
  2. Pick an element in the array to serve as a “pivot” point. (Usually the left-most element in the array is used.)
  3. Split the array into two parts – one with elements larger than the pivot and the other with elements smaller than the pivot.
  4. Recursively repeat the algorithm for both halves of the original array.

The quick sort is by far the fastest of the common sorting algorithms. It is possible to write a special-purpose sorting algorithm that can beat the quick sort for some data sets, but for general-case sorting there isn’t anything faster.

The quick sort is recursive, which can make it a bad choice for applications that run on machines with limited memory.

Quick Sort Routine

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int x;

// Quick Sort Algorithm
public void sortArray()
{
q_sort( 0, x-1 );
}

public void q_sort( int left, int right )
{
int pivot, l_hold, r_hold;

l_hold = left;
r_hold = right;
pivot = a[left];

while( left < right )
{
while( (a[right] >= pivot) && (left < right) )
{
right–;
}

if( left != right )
{
a[left] = a[right];
left++;
}

while( (a[left] <= pivot) && (left < right) )
{
left++;
}

if( left != right )
{
a[right] = a[left];
right–;
}
}

a[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;

if( left < pivot )
{
q_sort( left, pivot-1 );
}

if( right > pivot )
{
q_sort( pivot+1, right );
}
}

You can download the full code here, or the compiled code here.

for further go to : http://www.publicjoe.f9.co.uk/csharp/sort05.html

Advertisements

Actions

Information

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: