|
| 1 | +package sortingNSearching; |
| 2 | + |
| 3 | +public class QuickSort { |
| 4 | + public static void main(String[] args) { |
| 5 | + int num[] = new int[10]; |
| 6 | + for (int i = 0; i < num.length; ++i) { |
| 7 | + num[i] = (int) (Math.random() * 100); |
| 8 | + } |
| 9 | + |
| 10 | + // before sort |
| 11 | + System.out.println("Before sort : "); |
| 12 | + for (int i = 0; i < num.length; ++i) |
| 13 | + System.out.print(num[i] + " "); |
| 14 | + |
| 15 | + System.out.println("\n after sort : "); |
| 16 | + |
| 17 | + int helper[] = new int[num.length]; |
| 18 | + |
| 19 | + quickSort(num, 0, num.length - 1); |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | + for (int i = 0; i < num.length; ++i) |
| 24 | + System.out.print(num[i] + " "); |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + private static void quickSort(int[] num, int low, int high) { |
| 29 | + if (low < high) { |
| 30 | + int index = partition(num, low, high); |
| 31 | + if (low < index - 1) |
| 32 | + quickSort(num, low, index - 1);// sort left half |
| 33 | + if (index < high) |
| 34 | + quickSort(num, index, high);// sort right half |
| 35 | + } |
| 36 | + |
| 37 | + } |
| 38 | + |
| 39 | + private static int partition(int[] num, int low, int high) { |
| 40 | + int pivot = num[low + (high - low) / 2]; |
| 41 | + while (low <= high) { |
| 42 | + // find first element from left which should be on right |
| 43 | + while (num[low] < pivot) |
| 44 | + ++low; |
| 45 | + |
| 46 | + // find first element from right which should be on left |
| 47 | + while (num[high] > pivot) |
| 48 | + --high; |
| 49 | + |
| 50 | + // swap elements and move left and right indices |
| 51 | + if (low <= high) { |
| 52 | + int temp = num[high]; |
| 53 | + num[high] = num[low]; |
| 54 | + num[low] = temp; |
| 55 | + ++low; |
| 56 | + --high; |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + } |
| 61 | + return low; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments