快速排序的基本思想:
通過一趟排序?qū)⒋判蛴涗浄指畛瑟?dú)立的兩部分,其中一部分記錄的關(guān)鍵字均比另一部分關(guān)鍵字小,則分別對這兩部分繼續(xù)進(jìn)行排序,直到整個(gè)序列有序。
先看一下這幅圖:
把整個(gè)序列看做一個(gè)數(shù)組,把第零個(gè)位置看做中軸,和最后一個(gè)比,如果比它小交換,比它大不做任何處理;交換了以后再和小的那端比,比它小不交換,比他大交換。這樣循環(huán)往復(fù),一趟排序完成,左邊就是比中軸小的,右邊就是比中軸大的,然后再用分治法,分別對這兩個(gè)獨(dú)立的數(shù)組進(jìn)行排序。
- public int getMiddle(Integer[] list, int low, int high) {
- int tmp = list[low]; //數(shù)組的第一個(gè)作為中軸
- 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數(shù)組進(jìn)行一分為二
- _quickSort(list, low, middle - 1); //對低字表進(jìn)行遞歸排序
- _quickSort(list, middle + 1, high); //對高字表進(jìn)行遞歸排序
- }
- }
- public void quick(Integer[] str) {
- if (str.length > 0) { //查看數(shù)組是否為空
- _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();
- }
- }
2 3 7 10 14 23 34 53
這樣就排序好了,快速排序是對冒泡排序的一種改進(jìn),平均時(shí)間復(fù)雜度是O(nlogn)。