对于快排,无论是看别人面经,还是自己亲身的笔试面试经历,都是经常会遇到的。所以在此,本人仅通过博客的形式记录下来,以便自己查阅,或给其他有需要的人用作参考也好。
public class SortMethods {
/**
<span style="white-space:pre"> </span> * @author PursueCloud
<span style="white-space:pre"> </span> * 常见排序算法
<span style="white-space:pre"> </span> * 当数据基本无序:①8, 5, 7, 1, 99, 44, 78, 22(比较次数16次)
<span style="white-space:pre"> </span> *数据换成基本有序的数组时,比较次数会增加,如:
<span style="white-space:pre"> </span> *<span style="white-space:pre"> </span> ②5, 1, 8, 7, 22, 44, 78, 99(18次)
<span style="white-space:pre"> </span> *<span style="white-space:pre"> </span> ③1, 5, 7, 8, 22, 44, 78, 99(28次)
<span style="white-space:pre"> </span> */<span style="white-space:pre"> </span>
public static void main(String[] args) {
int[] testData = {8, 5, 7, 1, 99, 44, 78, 22};
int[] dataSorted = quickSort(testData, 0, testData.length-1);
for(int a : dataSorted) {
System.out.print(a + " ");
}
System.out.println("比较次数:" + cnt);
}
/**
* 快速排序
*/
static int cnt = 0;
private static int partition(int[] data, int low, int high) {
int key = data[low];
while(low < high) {
while(low<high && data[high]>=key) {
high--;
cnt++;
}
data[low] = data[high];//(此时因low=high或data[high]<key)将high下标处的数赋给low下标处的数,保证data[low]<key
while(low<high && data[low]<=key) {
low++;
cnt++;
}
data[high] = data[low];//(此时因low=high或data[low]>key)将low下标处的数赋给high下标处的数,保证data[high]>key
}
data[low] = key;
return low;
}
public static int[] quickSort(int[] data, int low, int high) {
if(low < high) {
int result = partition(data, low, high);
quickSort(data, low, result-1);//对low到result-1下标间数进行排序
quickSort(data, result+1, high);//对result+1到high下标间数进行排序
}
return data;
}
快排的时间复杂度,最好的情况下是O(nlgn),最坏的情况下位O(n^2)。当待排序数据基本无序时,快排的速度是最快的,而当数据是基本有序时,其反而是最慢的。如上,虽然可能通过累加比较次数的方法来比较其在数据有序或无序的不同情况下的时间复杂度可能有点不严谨,不过对我来说是最直观的。如上面通过排序不同数据得出的结果,数据为基本无序的数据①时cnt的值为16,基本有序的数据②为18,已经排序完毕的③时为28,这个结果也证实了前面所说:“”当待排序数据基本无序时,快排的速度是最快的,而当数据是基本有序时,其反而是最慢的。”
PS:以上若有不妥,谢谢指出