参考:搜狗百科 快速排序
特点:
基于分治法,选取某一个元素作为主元,将原集合分为三部分:左边集合的元素都小于等于主元,主元,右边集合的元素都大于等于主元。
然后利用递归思想,对左右两边的集合分别进行快速排序。
快速排序在一般情况下是最实用的排序方法之一。算法在最坏的情况下运行时间为O(n^2),平均时间复杂度为O(nlogn)。。空间复杂度为S(1),即常数级空间。但需要注意递归栈上需要花费最少logn 最多n的空间。
所有基于比较方法的排序方法的时间下界不会低于O(nlogn)
基本方法:
选取第一个元素作为主元。
Java代码实现:
public void startQuitSort(int[] nums) {
quitSort(nums, 0, nums.length - 1);
int i = 0;
while(i < nums.length){
System.out.println(nums[i++]);
}
}
public void quitSort(int[] nums, int low, int high) {
if (low > high) {
return;
}
int pos = findPos(nums, low, high);
if (pos < 0) {
return;
}
quitSort(nums, low, pos - 1);
quitSort(nums, pos + 1, high);
}
public int findPos(int[] nums, int low, int high) {
if (low > high || high >= nums.length) {
return -1;
}
int baseIndex = low;
int baseValue = nums[low];
while(low < high){
while (high > low && nums[high] >= baseValue){
high--;
}
while(low < high && nums[low] <= baseValue){
low++;
}
swap(nums,low,high);
}
swap(nums,low,baseIndex);
return low;
}
private void swap(int[]nums,int from, int to){
if(nums == null || to >= nums.length || from >= nums.length){
return;
}
int temp = nums[from];
nums[from] = nums[to];
nums[to] = temp;
}
随机化的快速排序法
优缺点:
快速排序的最坏情况基于每次划分对主元的选择。基本的快速排序选取第一个元素作为主元。这样在数组已经有序的情况下,每次划分将得到最坏的结果。一种比较常见的优化方法是随机化算法,即随机选取一个元素作为主元。这种情况下虽然最坏情况仍然是O(n^2),但最坏情况不再依赖于输入数据。实际上,随机化快速排序得到理论最坏情况的可能性仅为1/(2^n)。所以随机化快速排序可以对于绝大多数输入数据达到O(nlogn)的期望时间复杂度。
Java代码实现:
public void startQuitSort(int[] nums) {
quitSort(nums, 0, nums.length - 1);
int i = 0;
while(i < nums.length){
System.out.println(nums[i++]);
}
}
public void quitSort(int[] nums, int low, int high) {
if (low > high) {
return;
}
int pos = findPos(nums, low, high);
if (pos < 0) {
return;
}
quitSort(nums, low, pos - 1);
quitSort(nums, pos + 1, high);
}
public int findPos(int[] nums, int low, int high) {
if (low > high || high >= nums.length) {
return -1;
}
Random random = new Random(high-low);
int baseIndex = low + random.nextInt(high-low+1);
int baseValue = nums[baseIndex];
boolean leftFirst = false;
if(Math.abs(high - baseIndex) < Math.abs(baseIndex - low)){
leftFirst = true;
}
while(low < high){
if(leftFirst){
while(low < high && nums[low] <= baseValue){
low++;
}
while (high > low && nums[high] >= baseValue){
high--;
}
} else{
while (high > low && nums[high] >= baseValue){
high--;
}
while(low < high && nums[low] <= baseValue){
low++;
}
}
swap(nums,low,high);
}
swap(nums,low,baseIndex);
return low;
}
private void swap(int[]nums,int from, int to){
if(nums == null || to >= nums.length || from >= nums.length){
return;
}
int temp = nums[from];
nums[from] = nums[to];
nums[to] = temp;
}