快速排序
快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists)。
快速排序又是一种分而治之思想在排序算法上的典型应用。本质上来看,快速排序应该算是在冒泡排序基础上的递归分治法。
public class Test { public static void main(String[] args) { int[] arr = {49, 38, 65, 97, 23, 76, 1}; quickSort(arr, 0, arr.length - 1); System.out.println("排序后:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void quickSort(int[] arr, int low, int high) { if (low >= high) { return; } int index = getIndex(arr, low, high); quickSort(arr, low, index - 1); quickSort(arr, index + 1, high); } public static int getIndex(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; } }