|
| 1 | +package sort; |
| 2 | + |
| 3 | +import static sort.SortUtils.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * |
| 7 | + * @author Varun Upadhyay (https://github.com/varunu28) |
| 8 | + * @author Podshivalov Nikita (https://github.com/nikitap492) |
| 9 | + * |
| 10 | + */ |
| 11 | +class QuickSort implements SortAlgorithm { |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | + /** |
| 16 | + * This method implements the Generic Quick Sort |
| 17 | + * |
| 18 | + * @param array The array to be sorted |
| 19 | + * Sorts the array in increasing order |
| 20 | + **/ |
| 21 | + |
| 22 | + @Override |
| 23 | + public <T extends Comparable<T>> T[] sort(T[] array) { |
| 24 | + doSort(array, 0, array.length - 1); |
| 25 | + return array; |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + /** |
| 30 | + * The sorting process |
| 31 | + * |
| 32 | + * @param left The first index of an array |
| 33 | + * @param right The last index of an array |
| 34 | + * @param array The array to be sorted |
| 35 | + * |
| 36 | + **/ |
| 37 | + |
| 38 | + private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) { |
| 39 | + if (left < right) { |
| 40 | + int pivot = partition(array, left, right); |
| 41 | + doSort(array, left, pivot - 1); |
| 42 | + doSort(array, pivot , right); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * This method finds the partition index for an array |
| 48 | + * |
| 49 | + * @param array The array to be sorted |
| 50 | + * @param left The first index of an array |
| 51 | + * @param right The last index of an array |
| 52 | + * Finds the partition index of an array |
| 53 | + **/ |
| 54 | + |
| 55 | + private static <T extends Comparable<T>> int partition(T[] array, int left, int right) { |
| 56 | + int mid = (left + right) / 2; |
| 57 | + T pivot = array[mid]; |
| 58 | + |
| 59 | + while(left <= right) { |
| 60 | + while(less(array[left], pivot)){ |
| 61 | + ++left; |
| 62 | + } |
| 63 | + while(less(pivot, array[right])) { |
| 64 | + --right; |
| 65 | + } |
| 66 | + if(left <= right) { |
| 67 | + swap(array, left, right); |
| 68 | + ++left; |
| 69 | + --right; |
| 70 | + } |
| 71 | + } |
| 72 | + return left; |
| 73 | + } |
| 74 | + |
| 75 | + // Driver Program |
| 76 | + public static void main(String[] args) { |
| 77 | + |
| 78 | + // For integer input |
| 79 | + Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12 ,2, 5 ,7 ,8 ,9, 2, 44, 111, 5}; |
| 80 | + |
| 81 | + QuickSort quickSort = new QuickSort(); |
| 82 | + // quickSort.sort(array); |
| 83 | + |
| 84 | + //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 |
| 85 | + print(array); |
| 86 | + |
| 87 | + String[] stringArray = {"c", "a", "e", "b", "d"}; |
| 88 | + quickSort.sort(stringArray); |
| 89 | + |
| 90 | + //Output => a b c d e |
| 91 | + print(stringArray); |
| 92 | + } |
| 93 | +} |
| 94 | + |
0 commit comments