快速排序的思想:
1、先找一個樞軸,使得整個數組的右邊的數都大於等於這個數,數組左邊的數都小於等於這個數
2、然後採用分治法對這個數兩邊的兩段數組採用上述相同的方法進行排序
概括起來就是先對數組進行partion,找到下一個樞軸的位置,然後再對左右兩邊遞歸進行sort。
下面是快速排序算法的Java實現源碼:
import java.util.Arrays;
/*
* 創建一個快速排序的實現類
*
* * */
public class QuickSort {
/*
* 創建一個基於遞歸的快速排序方法
* 方法輸入:待排序數組a,待排序數組下界,待排序數組上界
*
* */
public void Sort(int[] a,int l, int r) {
//邊界檢測,數組下界必須小於上界,纔有必要進行下一次快排
if(l < r) {
int i = l, j = r, temp = a[i];
//挖坑填坑部分
while(i < j) {
while(i < j && a[j] >= temp) {
j--;
}
if (a[j] < temp) {
a[i] = a[j];
i++;
}
while(i < j && a[i] < temp) {
i++;
}
if (a[i] > temp) {
a[j] = a[i];
j--;
}
}
a[i] = temp;
//分治法遞歸進行左右兩邊快排
Sort(a,l,i-1);
Sort(a,i+1,r);
}
}
/*
* 程序主函數,進行類方法調用
*
* */
public static void main(String [] args) {
int [] a = {1,5,9,6,10,8,3,2};
QuickSort quickSort = new QuickSort();
quickSort.Sort(a, 0, a.length-1);
//將數組轉換爲字符串輸出
System.out.println(Arrays.toString(a));
}
}