public class QuickSort {
public static void main(String[] args) {
QuickSort obj = new QuickSort();
int[] a = new int[] {3,5,2,7,6,1};
// int[] a = new int[] {1,2,10,4,5};
obj.quickSort(a, 0, a.length-1);
//System.out.println("sorted array ==" + a.toString());
}
public void swap(int[] a, int index1, int index2){
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public int partition(int[] a, int low, int high){
int pivot = a[high];
int m = low;
for(int i=low; i <= high-1; i++){
if(a[i] < pivot){
//put all elements less than pivot to the left of pivot
swap(a, i, m);
m++;
}
}
swap(a, m, high);
return m;
}
public void quickSort(int[] a, int low, int high){
if(low < high){
int pivot = partition(a, low, high);
quickSort(a, low, pivot-1);
quickSort(a, pivot+1, high);
}
}
}
Saturday, July 23, 2016
Quicksort
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment