|  | 
| 3 | 3 | import java.util.Arrays; | 
| 4 | 4 | 
 | 
| 5 | 5 | public class QuickSort { | 
| 6 |  | - | 
|  | 6 | +  | 
| 7 | 7 |  public void sort(int[] array) { | 
| 8 | 8 |  if (array.length < 2) { | 
| 9 | 9 |  return; | 
| 10 | 10 |  } | 
| 11 | 11 | 
 | 
| 12 | 12 |  quickSort(array, 0, array.length - 1); | 
|  | 13 | + System.out.println(swaps); | 
| 13 | 14 |  } | 
| 14 | 15 | 
 | 
| 15 | 16 |  private void quickSort(int[] array, int min, int max) { | 
| 16 | 17 |  // Base case, partition is of size one or null | 
| 17 |  | - if (min >= max) { | 
|  | 18 | + if (min > max) { | 
| 18 | 19 |  return; | 
| 19 | 20 |  } | 
| 20 | 21 | 
 | 
| 21 |  | - // Set starting pivot at last position | 
| 22 |  | - int pivot = max; | 
|  | 22 | + // Reorder partition so that x < pivot on the left and x >= pivot on the right | 
|  | 23 | + // Returned int is the index of the pivot | 
|  | 24 | + int pivot = partition(array, min, max); | 
|  | 25 | + | 
|  | 26 | + // Recursively apply quick sort to left and right side of list | 
|  | 27 | + quickSort(array, min, pivot - 1); | 
|  | 28 | + quickSort(array, pivot + 1, max); | 
|  | 29 | + } | 
|  | 30 | + | 
|  | 31 | + private int partition(int[] array, int min, int max) { | 
|  | 32 | + int pivot = array[max]; | 
| 23 | 33 |  int left = min; | 
| 24 | 34 |  int right = max; | 
| 25 | 35 | 
 | 
| 26 | 36 |  // Repeat until pointers meet | 
| 27 |  | - while (left < right) { | 
| 28 |  | - // Continue until left side swap candidate is found | 
| 29 |  | - while (array[left] < array[pivot]) { | 
|  | 37 | + while (true) { | 
|  | 38 | + // Keep moving left pointer until swap candidate is found | 
|  | 39 | + while (array[left] < pivot) { | 
| 30 | 40 |  left++; | 
| 31 | 41 |  } | 
| 32 |  | - | 
| 33 |  | - // Swap and update pivot index | 
| 34 |  | - swap(array, left, pivot); | 
| 35 |  | - pivot = left; | 
| 36 |  | - | 
| 37 |  | - // Continue until right side swap candidate is found | 
| 38 |  | - while (array[right] > array[pivot]) { | 
|  | 42 | + // Same for right pointer | 
|  | 43 | + while (array[right] > pivot) { | 
| 39 | 44 |  right--; | 
| 40 | 45 |  } | 
| 41 | 46 | 
 | 
| 42 |  | - // Swap and update pivot index | 
| 43 |  | - swap(array, right, pivot); | 
| 44 |  | - pivot = right; | 
|  | 47 | + // If pointers met, we're done on this partition, pivot is on right pointer | 
|  | 48 | + if (left >= right) { | 
|  | 49 | + return right; | 
|  | 50 | + } | 
|  | 51 | + | 
|  | 52 | + // Swap elements | 
|  | 53 | + swap(array, left, right); | 
| 45 | 54 |  } | 
| 46 |  | - | 
| 47 |  | - // Recursively apply quick sort to left and right side of list | 
| 48 |  | - quickSort(array, min, pivot - 1); | 
| 49 |  | - quickSort(array, pivot + 1, max); | 
| 50 | 55 |  } | 
| 51 |  | - | 
| 52 | 56 | 
 | 
| 53 | 57 |  private void swap(int[] array, int a, int b) { | 
| 54 | 58 |  int temp = array[a]; | 
|  | 
0 commit comments