在数据处理方面,排序是很多算法的基础,很多处理操作都是在排序的基础上进行。很多刚开始学习编程的朋友可能只知道选择和冒泡排序。这两种排序算法在小数据量的时候还可以,在大数据面前需要的时间也是海量的。下面是大数据常用算法,快速排序的java实现(基于字符串hash值的顺序排序 ,下面会标注排序不同的数据需要改写的比较代码,只需要改写比较代码就能实现不同数据的排序) 


快速排序(Quicksort)是对 冒泡排序的一种改进。


快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以 递归进行,以此达到整个数据变成有序 序列。


/**
* 快速排序,此方法是递归将一个数组分成两段,前面的都小于中间的值,后面的都大于中中间的值,有缺陷,对重复的数据排序速度过慢
* @param strs 待排序的字符串
* @param low 能达到的最小索引
* @param high 能达到的最大索引
*/
@Deprecated
public static void quickSort(String strs[], int low, int high) {


if (strs == null || strs.length < 1) {
return;
}
if (low < high) {
int mid = getMid(strs, low, high);
quickSort(strs, low, mid - 1);
quickSort(strs, mid + 1, high);
}
}
/**
* 快速排序时分段,将比第一个大的都放后面,比第一个小的都放前面,并返回中间点(开始时候的第一个被换到的索引)
* @param strs
* @param low
* @param high
* @return
*/
@Deprecated
private static int getMid(String[] strs, int low, int high) {
String temp = strs[low];
while (low < high) {
while (low < high && strs[high].hashCode() > temp.hashCode()) {//这里是排序的比较代码,和下面一句比较代码的大于小于互换就能变为逆序
high--;
}
strs[low] = strs[high];
while (low < high && strs[low].hashCode() <= temp.hashCode()) {//比较代码2
low++;
}
strs[high] = strs[low];
}
strs[low] = temp;
return low;
}





上面这种方法是快速排序的基本实现,但是当数据中相等的数据太多的时候,每次将划分两部分一部分过小,一部分过大,效率和冒泡排序类似。下面是改进版。如果其选中的中间数据碰到相等的数据的话会将相等的数据聚合到一起再对剩下的两部分数据进行排序


/**
* 简单优化版的快速排序,
* @param arr 待排序数组
* @param low 能达到最低索引
* @param high 能达到最高索引
*/
public static void quickSortPlus(String[] arr, int low, int high) {


if (low >= high)
return;
int lt = low;
int gt = high;
String temp = arr[low];
int i = low + 1;
while (i <= gt) {
if (arr[i].hashCode() < temp.hashCode()) {//比较代码1
swap(arr, lt, i);
lt++;
i++;
} else if (arr[i].hashCode() > temp.hashCode()) {//比较代码2
swap(arr, gt, i);
gt--;
} else {
i++;
}
}
quickSortPlus(arr, low, lt - 1);
quickSortPlus(arr, gt + 1, high);


}