publicclassMain{ publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = newint[n]; for (int i = 0; i < n; ++i) { nums[i] = sc.nextInt(); } quickSort(nums, 0, n - 1); for (int i = 0; i < n; ++i) { System.out.printf("%d ", nums[i]); } }
publicstaticvoidquickSort(int[] nums, int left, int right){ if (left >= right) { return; } int i = left - 1, j = right + 1; int x = nums[left]; while (i < j) { while (nums[++i] < x); while (nums[--j] > x); if (i < j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } quickSort(nums, left, j); quickSort(nums, j + 1, right); } }
@Test publicvoidtest(){ int[] str={6,5,4,8,9,7,2,1,3,0}; int left=0; int right=9; quicksort(str,left,right); for (int i : str) { System.out.println(i); } } publicvoidquicksort(int[] nums, int left, int right){ if (left >= right) { return; } int i = left - 1, j = right + 1; int x = nums[left]; while (i < j) { while (nums[++i] < x) { ; } while (nums[--j] > x) { ; } if (i < j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } quicksort(nums, left, j); quicksort(nums, j + 1, right); }
通用模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
voidquickSort(int[] nums, int left, int right){ if (left >= right) { return; } int i = left - 1, j = right + 1; int x = nums[left]; while (i < j) { while (nums[++i] < x); while (nums[--j] > x); if (i < j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } quickSort(nums, left, j); quickSort(nums, j + 1, right); }