說來感到慚愧,昨天看別人的博客上面一一講了一些算法,其實這些算法在大學都學過,不過幾乎全部忘記了。雖然現在做java上層開發基本上用不到算法,但是還是感覺算法是一種思想,是一種靈魂,所以又不僅翻開了嚴蔚敏老師的數據結構,一個一個把以前忘記的算法實現一遍。
快速排序的基本思想:
通過一趟排序將待排序記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分關鍵字小,則分別對這兩部分繼續進行排序,直到整個序列有序。
先看一下這幅圖:

把整個序列看做一個數組,把第零個位置看做中軸,和最后一個比,如果比它小交換,比它大不做任何處理;交換了以后再和小的那端比,比它小不交換,比他大交換。這樣循環往復,一趟排序完成,左邊就是比中軸小的,右邊就是比中軸大的,然后再用分治法,分別對這兩個獨立的數組進行排序。
- public int getMiddle(Integer[] list, int low, int high) {
- int tmp = list[low]; //數組的第一個作為中軸
- while (low < high) {
- while (low < high && list[high] > tmp) {
- high--;
- }
- list[low] = list[high]; //比中軸小的記錄移到低端
- while (low < high && list[low] < tmp) {
- low++;
- }
- list[high] = list[low]; //比中軸大的記錄移到高端
- }
- list[low] = tmp; //中軸記錄到尾
- return low; //返回中軸的位置
- }
public int getMiddle(Integer[] list, int low, int high) {
int tmp = list[low]; //數組的第一個作為中軸
while (low < high) {
while (low < high && list[high] > tmp) {
high--;
}
list[low] = list[high]; //比中軸小的記錄移到低端
while (low < high && list[low] < tmp) {
low++;
}
list[high] = list[low]; //比中軸大的記錄移到高端
}
list[low] = tmp; //中軸記錄到尾
return low; //返回中軸的位置
}
遞歸形式的分治排序算法:
- public void _quickSort(Integer[] list, int low, int high) {
- if (low < high) {
- int middle = getMiddle(list, low, high); //將list數組進行一分為二
- _quickSort(list, low, middle - 1); //對低字表進行遞歸排序
- _quickSort(list, middle + 1, high); //對高字表進行遞歸排序
- }
- }
public void _quickSort(Integer[] list, int low, int high) {
if (low < high) {
int middle = getMiddle(list, low, high); //將list數組進行一分為二
_quickSort(list, low, middle - 1); //對低字表進行遞歸排序
_quickSort(list, middle + 1, high); //對高字表進行遞歸排序
}
}
- public void quick(Integer[] str) {
- if (str.length > 0) { //查看數組是否為空
- _quickSort(str, 0, str.length - 1);
- }
- }
public void quick(Integer[] str) {
if (str.length > 0) { //查看數組是否為空
_quickSort(str, 0, str.length - 1);
}
}
編寫測試方法:
- public class TestMain {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Integer[] list={34,3,53,2,23,7,14,10};
- QuicSort qs=new QuicSort();
- qs.quick(list);
- for(int i=0;i<list.length;i++){
- System.out.print(list[i]+" ");
- }
- System.out.println();
- }
-
- }
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] list={34,3,53,2,23,7,14,10};
QuicSort qs=new QuicSort();
qs.quick(list);
for(int i=0;i<list.length;i++){
System.out.print(list[i]+" ");
}
System.out.println();
}
}
看一下打印結果吧:
2 3 7 10 14 23 34 53
這樣就排序好了,快速排序是對冒泡排序的一種改進,平均時間復雜度是O(nlogn)。
posted on 2013-04-11 00:30
fly 閱讀(208)
評論(0) 編輯 收藏 所屬分類:
算法