|
| 1 | +/** |
| 2 | + * Quick sort an integer arrays |
| 3 | + * |
| 4 | + * Tags: Sort |
| 5 | + */ |
| 6 | +class QuickSort { |
| 7 | + public static void main(String[] args) { |
| 8 | + QuickSort q = new QuickSort(); |
| 9 | + int[] A = { 1, 4, 2, 8, 5}; |
| 10 | + q.sort(A, 0, A.length - 1); |
| 11 | + for (int n : A) System.out.print(n + ","); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * Partition the array according to middle index |
| 16 | + * Sort left half, from left to index - 1 |
| 17 | + * Sort right half, from index to right |
| 18 | + */ |
| 19 | + public void sort(int[] A, int left, int right) { |
| 20 | + int index = partition(A, left, right); |
| 21 | + if (left < index - 1) sort(A, left, index - 1); |
| 22 | + if (index < right) sort(A, index, right); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Choose pivot |
| 27 | + * Init 2 pointers from both ends to do partition |
| 28 | + * Move left pointer if A[left] is smaller than pivot(skip smaller) |
| 29 | + * Move right pointer if A[right] is bigger than pivot(skip bigger) |
| 30 | + * Check if left <= right, if so, swap left and right, move them |
| 31 | + * Return left index |
| 32 | + */ |
| 33 | + private int partition(int[] A, int left, int right) { |
| 34 | + int pivot = A[left + (right - left) / 2]; |
| 35 | + while (left <= right) { |
| 36 | + while (A[left] < pivot) left++; |
| 37 | + while (A[right] > pivot) right--; |
| 38 | + if (left <= right) { |
| 39 | + int temp = A[left]; |
| 40 | + A[left] = A[right]; |
| 41 | + A[right] = temp; |
| 42 | + left++; |
| 43 | + right--; |
| 44 | + } |
| 45 | + } |
| 46 | + return left; |
| 47 | + } |
| 48 | +} |
0 commit comments