快速排序算法是基于分支策略的另一个排序算法。其基本思想是,对于输入的子数组a[left,right],按一下步骤排序:
(1)分解:以a[i]为基准将a[left,right]划分为3段a[left,i-1],a[i],a[i+1,right],使得a[left,i-1]中的任何一个元素小于等于a[i],a[i+1,right]中的任何元素大于等于a[i]。下标i在划分过程中确定。
(2)递归求解,通过递归用快速排序算法,分别对a[left,i-1]和a[i+1,right]进行排序。
(3)合并,由于对a[left,i-1]和a[i+1,right]的排序是就地进行的,所以在a[left,i-1]和a[i+1,right]都已排好的序后不需要执行任何计算,a[left,right]就已排好序。
package edu.xalead;
import java.util.Arrays;
public class 快速排序 {
static void qSort(int a[], int left, int right) {
if (left < right) {
int i = left;
int j = right;
int temp = a[left];
while (i < j) {
// 将小于temp的元素交换到左边区域
while (a[j] >= temp && i < j) j--;
if (i < j) {
a[i] = a[j];
i++;
}
// 将大于temp的元素交换到右边区域
while (a[i] < temp && i < j) i++;
if (i < j) {
a[j] = a[i];
j--;
}
}
a[i] = temp;
qSort(a, left, i - 1); // 对左半段进行排序
qSort(a, i + 1, right); // 对右半段进行排序
}
}
public static void main(String[] args) {
int[] a = {21435, 4365, 0, -325, 56577};
System.out.println("排序前:\n" + Arrays.toString(a));
qSort(a,0,4);
System.out.println("排序后:\n" + Arrays.toString(a));
}
}
测试结果:
- 第二种源码:
package edu.xalead.InsertironSort;
public class QuickSort {
public static void main(String[] args) {
int[] a = {87,45,78,32,17,65,53,9,122,1,88};
printArray(a);
quicktSort(0,a.length-1,a);
printArray(a);
}
private static void quicktSort(int low, int high, int[] a) {
if(low<high){
int middle = getMiddle(low,high,a);
quicktSort(low,middle-1,a);
quicktSort(middle+1,high,a);
}
}
private static int getMiddle(int low, int high, int[] a) {
int temp = a[low];
while(low<high){
while (a[high]>=temp&&low<high){
high--;
}
a[low] = a[high];
low++;
while (a[low]<=temp&&low<high){
low++;
}
a[high] = a[low];
}
a[high] = temp;
return high;
}
private static void printArray(int[] a) {
for(int i:a){
System.out.print(i + " ");
}
System.out.println();
}
}
时间复杂度的相关分析:
package edu.xalead;
import java.util.Arrays;
public class 快速排序 {
private static void qSort(int[] a, int p, int r) {
if (p < r) {
int q = partition(a, p, r);
qSort(a, p, q - 1);
qSort(a, q + 1, r);
}
}
private static int partition(int[] a, int p, int r) {
int i = p, j = r + 1;
int temp = a[p];
while (p < r) {
while (a[r] > temp && p < r) r--;
if (p < r) {
a[i] = a[r];
i++;
}
while (a[i] < temp && i < r) i++;
if (p < r) {
a[r] = a[i];
r--;
}
// if(i<r){
//
// }
// while(a[++i].compareTo(x)<0&&i<r);
// while(a[--j].compareTo(x)>0);
// if(i>j) break;
// MyMath.swap(a,i,j);
a[i] = temp;
}
return i;
}
public static void main(String[] args) {
int []a = {13,243,50,35,-6346,35,5,9};
System.out.println("排序前:" + Arrays.toString(a));
System.out.println("***********************************************************");
// StringBuilder sb = new StringBuilder("[(");
// for(int element:a){
// sb.append(element + ",") ;
// }
// sb.replace(sb.length()-2,sb.length(), ")]");
qSort(a,0,7);
partition(a,0,7);
System.out.println("排序后:" + Arrays.toString(a));
}
}