排序算法 -- 冒泡&快排
public static void main(String[] args) { int[] arr = {1, 2, 3, 6, 4, 7, 9, 10}; // 冒泡 int[] arr_1 = arr.clone(); bubble(arr_1); System.out.println(Arrays.toString(arr_1)); // 快排 int[] arr_2 = arr.clone(); quickSort(arr_2, 0, arr_2.length - 1); System.out.println(Arrays.toString(arr_2)); // } // region 冒泡 private static void bubble(int[] nums) { int idx = nums.length - 1; while (idx > 0) { for (int i = 0; i < idx; i++) { if (nums[idx] < nums[i]) { swap(nums, idx, i); } } idx--; } } // endregion // region 快排(分治思想) private static void quickSort(int[] nums, int low, int high) { if (low >= high) return;
int part = partition(nums, low, high); quickSort(nums, low, part - 1); quickSort(nums, part + 1, high); } // 基准分区 private static int partition(int[] nums, int low, int high) { int pivot = nums[low]; int left = low; int right = high + 1; while (true) { while (pivot < nums[--right]) { if (right == low) break; } while (pivot > nums[++left]) { if (left == high) break; } if (left >= right) break; swap(nums, left, right); } swap(nums, low, right); return right; } // endregion // 交换工具方法 public static void swap(int[] nums, int l, int r) { int tmp = nums[l]; nums[l] = nums[r]; nums[r] = tmp; }