快速排序也是一个比较基本的排序,面试考算法的话,这个排序的命中率比较高,那么下面就说说快速排序。
1、基本思想:选择一个基准元素,通常是第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于基准元素,此时,基准元素在其排好序后的正确位置,然后再用同样的方法递归的排序划分的两部分。
这段话什么意思呢?我们举个例子来说说:
还是那个数组{3,5,2,10,1,7},最后的顺序依然是要求从左到右,从小到大,我们选第一个元素3作为基准元素,第一趟排序先拿3和最后一个7比较,发现3小于7,符合从小到大,7在基准元素3的右边,也符合排序思想,继续往前一位拿1和3比较,发现1小于3,那么不符合从小到大了,也不符合在右边的为比基准元素3大的排序思想,那么就将1和3互换位置,那么现在的数组是{1,5,2,10,3,7},那么现在已经换了位置,就只能从前面开始继续排序,比较1和3,符合从小到大,也符合比基准元素3小的在左边的排序思想,所以继续用5和3比较,发现5比3大,不符合从小到大,也不符合比3大的在3右边,就将5和3互换位置,现在的数组为{1,3,2,10,5,7},如此继续直到3在整个数组的中部,符合在左边的比3小,在右边的比3大,那么3的位置就确定了,那么就3左边的和右边的分别进行快速排序,直到整个数组排好。
快速排序是不稳定的排序,当数组基本有序,用快速排序反而不好,当数量大并且很无序的时候,用快速排序比较好。
下面来看一段实现代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/**
* 1、算法思想: 通过一趟排序将要排序的数据分割成独立的两部分, 其中一部分的所有数据都比另外一部分的所有数据都要小,
* 然后再按此方法对这两部分数据分别进行快速排序, 整个排序过程可以递归进行,以此达到整个数据变成有序序列。
* 会选择一个基准元素,此元素通常为第一个元素或者最后一个元素。
* 2、适用场景:快速排序是不稳定的排序。快速排序的时间复杂度为O(nlogn)。当n较大时使用快排比较好,当序列基本有序时用快排反而不好。
* 当数据较多较为杂乱的时候使用快速排序较好,当元素较少并且基本有序的时候,使用快速排序不好。
*/
public class QuickSort {
public void quickSort(int... args) {
if (args != null && args.length > 0) {
this.recursiveSort(0, args.length - 1, args);
}
}
/**
* 递归版本
*
* @param low
* @param high
* @param args
*/
private void recursiveSort(int low, int high, int... args) {
if (args != null && high < args.length && low >= 0 && low < high) {
int pivotIndex = this.partition(low, high, args);
this.recursiveSort(0, pivotIndex - 1, args);
this.recursiveSort(pivotIndex + 1, high, args);
}
}
private int partition(int low, int high, int... args) {
int pivotIndex = -1;
if (args != null && high < args.length && low >= 0 && low < high) {
int temp = args[low];
while (low < high) {
while (low < high && args[high] >= temp) {
high--;
}
args[low] = args[high];
while (low < high && args[low] <= temp) {
low++;
}
args[high] = args[low];
}
args[low] = temp;
pivotIndex = low;
}
return pivotIndex;
}
public static void main(String[] args) {
QuickSort qs = new QuickSort();
int[] array = {3, 5, 2, 10, 1, 7};
for (int temp : array) {
System.out.print(temp + " ");
}
System.out.println();
qs.quickSort(array);
for (int temp : array) {
System.out.print(temp + " ");
}
}
}
快速排序算法详解与实现
3007

被折叠的 条评论
为什么被折叠?



