Click here to Skip to main content
Click here to Skip to main content

QuickSort Algorithm using Generics in C# 2.0

By , 26 Oct 2006
 

Screen Shot of test program

Introduction

Quick Sort is the fastest sorting algorithm. Quick sort uses the divide and conquer strategy. In this algorithm, I have implemented the Quick Sort algorithm using Generics in C# 2.0.

Background

The Quick Sort algorithm has following 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.

Using the code

Generics in C# are similar to templates in C++. Using Generics, I can use the same piece of code for sorting int, float, and double. The Generics class for a Quick Sort is as follows:

public class QuickSort <T> where T:IComparable
{
    T[] input;
    
    public QuickSort(T[] values)
    {
        input = new T[values.Length];
        for (int i = 0; i < values.Length; i++)
        {
            input[i] = values[i];
        }
        
    }

    public T[] Output
    {
        get
        {
            return input;
        }
    }
    public void Sort()
    {
        Sorting(0, input.Length-1);
    }
    public int getPivotPoint(int begPoint, int endPoint)
    {
        int pivot = begPoint;
        int m = begPoint+1;
        int n = endPoint;
        while ((m < endPoint) && 
               (input[pivot].CompareTo(input[m]) >= 0))
        {
            m++;
        }

        while ((n > begPoint) && 
               (input[pivot].CompareTo(input[n]) <= 0))
        {
            n--;
        }
        while (m < n)
        {
            T temp = input[m];
            input[m] = input[n];
            input[n] = temp;

            while ((m < endPoint) && 
                   (input[pivot].CompareTo(input[m]) >= 0))
            {
                m++;
            }

            while ((n > begPoint) && 
                   (input[pivot].CompareTo(input[n]) <= 0))
            {
                n--;
            }

        }
        if (pivot != n)
        {
            T temp2 = input[n];
            input[n] = input[pivot];
            input[pivot] = temp2;
            
        }
        return n;

    }
    public void Sorting(int beg,int end)
    {
        if (end==beg)
        {
            return;
        }
        else
        {
            int pivot = getPivotPoint(beg,end);
            if(pivot > beg)
            Sorting(beg, pivot-1);
            if(pivot < end)
            Sorting(pivot+1, end);
        }
    }
}

Points of Interest

The CompareTo method is used for comparing the generic type variables. ‘<’ and ‘>’ cannot be used for comparing generic variables because it works only with certain types. As generic parameter can used as any type of parameter, it will throw a compiler error:

Operator '>' cannot be applied to operands of type 'T' and 'T'.

Operator '<' cannot be applied to operands of type 'T' and 'T'.

Reference

For more information on the Quick Sort algorithm, see here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

MaheshBabu.ap
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDo not use the first element for the pivot.memberQwertie16 May '11 - 18:59 
Pivoting on the first element is a terrible idea. It causes quicksort to run in worst-case time (O(N^2)) if the data is already sorted.
GeneralMy vote of 5memberThe_Ant3 Aug '10 - 15:21 
With a few modifications I had the sort working just some simple changes to fit my class structure. Without any other optimization I was able to sort 10 million ints in a test run in about 12 seconds. Once I optimizated and made some adjustments I was able to preform the same sort in around 6 seconds. This was a great time saver and I did not make too many changes. Thank you!
GeneralMy vote of 1memberAkhil Gurua19 Feb '10 - 7:38 
My vote for 1
GeneralQuestionable PerformancememberAtomicMonster5 Mar '08 - 5:07 
I used an implementation that was strictly limited to integers, then I used yours with an integer type, and the performance difference was huge. Given a list of 100,000 values, the int structure completed in 359.375 ms while this method was 2984.375 ms. I'm not sure if this is due to generics or the logic itself, but something is amiss here. For one thing, you are taking the time to copy all the values from one array to another - for 100,000 values, thats a huge timesink. While this gets the job done in terms of sorting, it is not (imho) a good implementation where performance is a concern. But, it is a good example of how to use generics in a standard method.
GeneralStatic it!memberk^s30 May '07 - 22:52 
I think that for having only one private value in the class, you can made it static
 
Something like this:
 

public static class QuickSorter where T : IComparable
{
public static T[] Sort(T[] values)
{
Sorting(0, values.Length - 1, ref values);
 
return values;
}
 
private static void Sorting(int beg, int end, ref T[] values)
{
if (end == beg)
{
return;
}
else
{
int pivot = getPivotPoint(beg, end, ref values);
if (pivot > beg)
Sorting(beg, pivot - 1, ref values);
if (pivot < end)
Sorting(pivot + 1, end, ref values);
}
 
}
 
private static int getPivotPoint(int begPoint, int endPoint, ref T[] values)
{
int pivot = begPoint;
int m = begPoint + 1;
int n = endPoint;
 
while ((m < endPoint) && (values[pivot].CompareTo(values[m]) >= 0))
{
m++;
}
 
while ((n > begPoint) && (values[pivot].CompareTo(values[n]) <= 0))
{
n--;
}
 
while (m < n)
{
T temp = values[m];
values[m] = values[n];
values[n] = temp;
 
while ((m < endPoint) && (values[pivot].CompareTo(values[m]) >= 0))
{
m++;
}
 
while ((n > begPoint) && (values[pivot].CompareTo(values[n]) <= 0))
{
n--;
}
 
}
 
if (pivot != n)
{
T temp2 = values[n];
values[n] = values[pivot];
values[pivot] = temp2;
 
}
 
return n;
}
 
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 26 Oct 2006
Article Copyright 2006 by MaheshBabu.ap
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid