import java.util.Random; public class QuickSort { private static final int ARR_SIZE = 10; public static void main(String[] args) { Random rd = new Random(); int arr[] = new int[ARR_SIZE]; for (int i = 0; i < arr.length; i++) { arr[i] = rd.nextInt(100); } System.out.println("before sorting arr is:"); display(arr); sort(arr); System.out.println("after sorting arr is:"); display(arr); } private static void sort(int[] arr) { if (arr.length > 0) quickSort(arr, 0, arr.length - 1); } private static void quickSort(int[] arr, int low, int high) { if (low < high) { // 长度大于1 int pivotLoc = partition(arr, low, high);// 将数组一分为二 quickSort(arr, low, pivotLoc - 1); // 对低子数组递归排序 quickSort(arr, pivotLoc + 1, high);// 对高子数组递归排序 } } private static int partition(int[] arr, int low, int high) { int pivotVal = arr[low]; // 用数组的第一个元素作枢轴 while (low < high) { // 从数组的两端交替地向中间扫描 while (low < high && arr[high] >= pivotVal) high--; swap(arr, low, high); // 将比枢轴小的元素移动到低端 while (low < high && arr[low] <= pivotVal) low++; swap(arr, low, high);// 将比枢轴大的元素移动到高端 } return low; // 返回枢轴所在的位置 } private static void swap(int[] arr, int low, int high) { int temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; } private static void display(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
快速排序的实现
最新推荐文章于 2020-07-15 22:09:56 发布