/*
* QuickSort
* Best case performance O(n log(n))
* Average case performance O(n log(n))
* Worst case performance O(n^2)
* Worst case space complexity O(log(n))
*/
public class QuickSortExample {
public static void main(String[] args) {
int[] array= {4,2,3,5,6,9};
recursiveQuickSort(array, 0, array.length-1);
for(int i:array){
System.out.println(i+" ");
}
}
private static void recursiveQuickSort(int[] array, int startIdx, int endIdx){
int idx = partition(array, startIdx, endIdx);
if(startIdx < idx-1){
recursiveQuickSort(array, startIdx, (idx-1));
}
if(endIdx > idx){
recursiveQuickSort(array, idx, endIdx);
}
}
private static int partition(int[] array, int leftPtr, int rightPtr){
int pivot = array[leftPtr];
while(leftPtr <= rightPtr){
while(array[leftPtr] < pivot){
leftPtr++;
}
while(array[rightPtr]>pivot){
rightPtr--;
}
if(leftPtr<=rightPtr){
int tmp = array[leftPtr];
array[leftPtr] = array[rightPtr];
array[rightPtr] = tmp;
leftPtr++;
rightPtr--;
}
}
return leftPtr;
}
}
Friday, May 22, 2015
Quick Sort Java Code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment