1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public class Code05_QuickSort {
public static void quickSort(int[] nums, int left, int right) { if (left < right) { int pIndex = partition(nums, left, right); quickSort(nums, left, pIndex - 1); quickSort(nums, pIndex + 1, right); } }
public static int partition(int[] nums, int left, int right) { int pivot = nums[left];
int i = left; int j = right;
while (i < j) { while (i < j && nums[j] >= pivot) { j--; } while (i < j && nums[i] <= pivot) { i++; } if (i < j) { swap(nums, i, j); }
} swap(nums, left, j); return j; }
public static void swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; }
public static void main(String[] args) { int[] arr = {0, 1, 2, 1, 5, 0, 3,2,1}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
|