快速排序是C.R.A.Hoare於1962年提出的一種劃分交換排序。它採用了一種分治的策略,通常稱其爲分治法(Divide-and-ConquerMethod)。
該方法的基本思想是:
1.先從數列中取出一個數作爲基準數。
2.分區過程,將比這個數大的數全放到它的右邊,小於或等於它的數全放到它的左邊。
3.再對左右區間重複第二步,直到各區間只有一個數。
先列出算法代碼:
/**
* 快速排序
* @param arr 要排序的數組
* @param low 往前
* @param high 往後
*/
public void sort(int[] arr, int low, int high) {
int l = low;
int h = high;
int povit = arr[low];
while (l < h) {
while (l < h && arr[h] >= povit)
h--;
if (l < h) {
int temp = arr[h];
arr[h] = arr[l];
arr[l] = temp;
l++;
}
while (l < h && arr[l] <= povit)
l++;
if (l < h) {
int temp = arr[h];
arr[h] = arr[l];
arr[l] = temp;
h--;
}
}
if (l > low) sort(arr, low, l - 1);
if (h < high) sort(arr, l + 1, high);
System.out.println("調用sort方法排序;數組內容:["+printArray(arr)+"],第二個參數:"+low+"第三個參數:"+high);
}
/**
* 進行排序方法測試
*/
@Test
public void test() {
int[] a = new int[] { 9, 15, 21, 12, 3, 11, 4, 32, 27 ,21};
sort(a, 0, a.length - 1);
}
/**
* 編寫一個方法,將數組的內容拼成字符串輸出
* @param arr 要輸出的數組
*/
public String printArray(int[] arr){
String result = "";
for(int i=0;i<arr.length;i++){
result += arr[i]+",";
}
return result;
}
運行後控制檯輸出:
調用sort方法排序;數組內容:[3,4,9,12,21,11,15,32,27,21,],第二個參數:0第三個參數:0
調用sort方法排序;數組內容:[3,4,9,12,21,11,15,32,27,21,],第二個參數:0第三個參數:1
調用sort方法排序;數組內容:[3,4,9,11,12,21,15,32,27,21,],第二個參數:3第三個參數:3
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,32,27,21,],第二個參數:5第三個參數:5
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:8第三個參數:8
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:7第三個參數:8
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:7第三個參數:9
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:5第三個參數:9
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:3第三個參數:9
調用sort方法排序;數組內容:[3,4,9,11,12,15,21,21,27,32,],第二個參數:0第三個參數:9
前面的都是方法遞歸調用產生的輸出,最後一行爲main方法進行調用的sort方法輸出的內容
具體意思後續再寫出來.