快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
实现代码:
package com.charles.algorithm; public class QuickSort { public static void main(String[] args) { int[] data = new int[] { 4, 6, 8, 2, 5, 1, 0, 4, 8, 2 }; quickSort3(data, 0, data.length - 1); for (int item : data) { System.out.print(item + " "); } System.out.println(); } // One: make the first item to be index public static void quickSort(int[] data, int low, int high) { if (low >= high) { return; } int clow = low, chigh = high; int index = data[low]; while (low < high) { while (low < high && data[high] >= index) { high--; } data[low] = data[high]; while (low < high && data[low] <= index) { low++; } data[high] = data[low]; } data[low] = index; quickSort(data, low + 1, chigh); quickSort(data, clow, high - 1); } // Two: make the middle item to be index public static void quickSort2(int[] data, int low, int high) { if (low >= high) { return; } int clow = low, chigh = high; int middle = (low + high) / 2; int index = data[middle]; while (low <= high) { while (low <= high && data[low] < index) { low++; } while (low <= high && data[high] > index) { high--; } if (low < high) { middle = data[low]; data[low++] = data[high]; data[high--] = middle; } else { low++; high--; } } quickSort2(data, clow, high); quickSort2(data, low, chigh); } // Three: make the middle item to be index public static void quickSort3(int[] data, int low, int high) { if (low >= high) { return; } int clow = low, chigh = high; int middle = (low + high) / 2; int index = data[middle]; while (low < high) { while (low < high && data[low] < index) { low++; } while (low < high && data[high] > index) { high--; } if (low < high) { middle = data[low]; data[low++] = data[high]; data[high--] = middle; } else { if (data[low] > index) { high--; } else { low++; } break; } } quickSort3(data, clow, high); quickSort3(data, low, chigh); } }