快速排序是冒泡排序的改进,效率比较高,基本思想也是两两相比较。
public class QuickSort { public static void main(String[] args) { int[] arr = {1, 4, 11, 63, 92, 2, -2, -3, -6, 0}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } public static void quickSort(int[] arr, int low, int high) { //当low和high是一个数的时候就结束 if (low >= high) { return; } //i和j从两头往中间靠,直到相等即结束 int i = low; int j = high; int key = arr[i];//基准值 while (i < j) { while (arr[j] >= key && i < j) { j--; } if (i < j) {//交换 int t; t = arr[i]; arr[i] = arr[j]; arr[j] = t; } while (arr[i] <= key && i < j) { i++; } if (i < j) {//交换 int t; t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } //对基准左侧集合重复执行 quickSort(arr, low, i - 1); //对基准右侧集合重复执行 quickSort(arr, i + 1, high); } } 排序结果:[-6, -3, -2, 0, 1, 2, 4, 11, 63, 92]