基本思想
快速排序利用了分治法思想。通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
基本过程
Java代码
import java.util.Arrays; public class QuickSort { public static void sort(int[] arr, int low, int high) { if (low < high) { // 将数组一分为二 int mid = getMid(arr, low, high); // 对低位的数组进行递归排序 sort(arr, low, mid - 1); // 对高位的数组进行递归排序 sort(arr, mid + 1, high); } } private static int getMid(int[] arr, int low, int high) { // 将第一个数作为基准 int temp = arr[low]; while (low < high) { while (low < high && arr[high] > temp) { high--; } // 把比基准小的数移到低端 arr[low] = arr[high]; while (low < high && arr[low] < temp) { low++; } // 把比基准大的数移到高端 arr[high] = arr[low]; } // 让基准记录到尾端 arr[low] = temp; // 返回基准的位置 return low; } public static void main(String[] args) { int[] arr = new int[] { 14, 12, 15, 13, 11, 16 }; sort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
算法分析
原文:https://www.cnblogs.com/ericz2j/p/10830327.html