Simple steps for the algorithm are:
- Pick an element, called a pivot, from the list.
- Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
- Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
Time complexity of the quick sort algorithm is O(n log n). And the worst case time complexity is O(n^2). Quicksort has a space complexity of O(log n).
Lets see a java program to do quick sort
public class QuickSort { public int[] data; public QuickSort(int[] data) { this.data = data; } public void sortMe() { this.sortMe(data, 0, data.length-1); } public void sortMe(int[] array, int start, int end) { int i=start; int k=end; if((end - start) < 1) //return if there is < 1 element return; int pivot = array[start]; //take an integer as pivot while(k > i) //while the left and right indices have not met { //from left to right find first element greater than pivot while(array[i] <= pivot && i <= end && k > i) i++; //from right to left find first element smaller than pivot while(array[k] > pivot && k >= start && k >= i) k--; //if left index is still smaller than right, swap the elements if(k > i) swap(array, i, k); } //swap the last element in the left partition with the pivot. swap(array, start, k); //quicksort left partition sortMe(array, start, k-1); //quicksort right partition sortMe(array, k+1, end); } public void swap(int[] array, int idx1, int idx2) { int temp=array[idx1]; array[idx1] = array[idx2]; array[idx2] = temp; } public void printMe(int[] data) { for(int x=0; x<data.length; x++) { System.out.print(data[x]+", "); } System.out.println(); } public static void main(String[] args) { int[] data = {9,2,6,4,11,88,66,44,55,32,23,5,32,10}; QuickSort qs = new QuickSort(data); System.out.print("Before Sorting : "); qs.printMe(data); qs.sortMe(); System.out.print("After Sorting : "); qs.printMe(qs.data); } }
No comments:
Post a Comment