Wednesday, August 27, 2008

Implementation of quicksort in java

Hello ~Friends~

Yesterday I was going through a wonderful lecture series on quick sort, check it out at Erik Demaine.
I found it very enchanting thought provoking. Although I did not understand all the Maths, but I think I understood most of it.
So here goes my implementation of quick sort in Java. Here's the program and explanation.

Explanation:
Quick sort is a sorting algorithm belonging to the divide and conquer family of algorithms. What this means is that recursion is used as a primary implementation technique.
Advantages of the quick sort algorithm.
1> Very fast, almost 3 times faster than insertion sort.
2> Very easy and intuitive implementation.

So here's how we do it:
1> We pick any element at random and swap it with the first element of the array.
2> The first element is made a pivot element and compared and swapped to all elements in the array, such that all elements to the left of pivot are <>pivot.
3> The 2 such sub-array are again portioned and sorted according to statement 1.

Here's the code.

package sorting;



public class QuickSortArray {

public void printArray(int[] array)
{
for(int i: array)
System.out.println(i);
}

public void quickSort(int[] array, int p, int q)
{
//The recursion break condition is when p > q.
if(p < q)
{
int r=partition(array, p, q);
quickSort(array, p, r-1);
quickSort(array, r+1, q);
}

}

public int partition(int[] array, int p, int q)
{
//I need to explain the first statement,
//What Prof Erik states in his lecture is that
//the worst runtimes for this algo are seen in case
//the array is already sorted.
//To guard against this posibility, we randomly swap the
//first element of the array with a random location within the
//sub-array. Please check http://www.catonmat.net/blog/mit-introduction-to-algorithms-part-three/
//for more details.

int number=(int)(p+(Math.random()*(q-p)));
swap(array, p, number);
//We firstly make the first element a pivot.
int pivot=array[p];
int i=p;

for(int j=p+1; j<=q; j++)
{
//When ever the value of a[j] < pivot we swap the value with i.
if(array[j] < pivot)
{

swap(array, ++i, j);
}

}
swap(array, p, i );

return i;
}

public void genrateRandom()
{
int number=(int)(Math.random()*10.0);
System.out.println(number);
}

public void swap(int[] array,int p, int q)
{
int temp;
temp=array[p];
array[p]=array[q];
array[q]=temp;
}


public static void main(String[] args) {
int array[]={20,2,7,34,1,10,15,35,62,12,45};

//(array, 0, number);
QuickSortArray swap=new QuickSortArray();
//int number=(int)(Math.random()*10.0);
//swap.swap(array, 0, number);
swap.printArray(array);
swap.quickSort(array, 0, 10);
System.out.println("After Sorting");
swap.printArray(array);


}

}

No comments: