基本模板
参考代码:
static void quickSort(int[] arr, int low, int high) { //左右边界 和 基准值 int i, j, temp; if (low > high) return; i = low; j = high; temp = arr[low]; //二分思想 while (i < j) { //右边界 while (temp <= arr[j] && i < j) j--; //左边界 while (temp >= arr[i] && i < j) i++; //满足二分条件 if (i < j) swap(arr, i, j); } //基准值 与 i,j相同位置交换 arr[low] = arr[i]; arr[i] = temp; //递归 左右 quickSort(arr, low, j - 1); quickSort(arr, i + 1, high); } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
测试:
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[] numArr = new int[N]; for (int i = 0; i < N; i++) { numArr[i] = sc.nextInt(); } quickSort(numArr, 0, N - 1); for (int element : numArr) { System.out.print(element + " "); } }
0.0分
1 人评分