|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class QuickSort { |
| 4 | + |
| 5 | + private int partition(int [] array, int low, int high) |
| 6 | + { |
| 7 | + int largest = array[high]; |
| 8 | + int i = low - 1 ; // i to keep track of smaller element |
| 9 | + |
| 10 | + for (int j = low; j < high; j++) |
| 11 | + { |
| 12 | + if (array[j] <= largest) |
| 13 | + { |
| 14 | + i++; |
| 15 | + //exchange array[i] and array[j] |
| 16 | + int temp = array[i]; |
| 17 | + array[i] = array[j]; |
| 18 | + array[j] = temp ; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + //exchange last smaller element with pivot |
| 23 | + int temp = array[i+1]; |
| 24 | + array[i+1] = array[high]; |
| 25 | + array[high] = temp; |
| 26 | + |
| 27 | + return i+1; |
| 28 | + } |
| 29 | + public void quickSort(int[] array, int low, int high) |
| 30 | + { |
| 31 | + if (low < high) |
| 32 | + { |
| 33 | + int pivot = partition(array,low,high); //pivot is the partitioning index |
| 34 | + |
| 35 | + //recursive sort two sub arrays around pivot |
| 36 | + quickSort(array,low, pivot-1); |
| 37 | + quickSort(array,pivot+1,high); |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + public void printSortedArray(int[] array) { |
| 44 | + Arrays.stream(array) |
| 45 | + .forEach(num-> System.out.print(" "+num)); |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String[] args) { |
| 49 | + int[] arr = {16,8,7,3,1,9,4}; |
| 50 | + QuickSort qs = new QuickSort(); |
| 51 | + qs.quickSort(arr,0,arr.length-1); |
| 52 | + qs.printSortedArray(arr); |
| 53 | + } |
| 54 | +} |
0 commit comments