排序算法[總結]

經常使用排序算法小記

排序算法不少地方都會用到,近期又從新看了一遍算法,並本身簡單地實現了一遍,特此記錄下來,爲之後複習留點材料。 java

廢話很少說,下面逐一看看經典的排序算法: 算法

 

1. 選擇排序 數組

選擇排序的基本思想是遍歷數組的過程當中,以 i 表明當前須要排序的序號,則須要在剩餘的 [i…n-1] 中找出其中的最小值,而後將找到的最小值與 i 指向的值進行交換。由於每一趟肯定元素的過程當中都會有一個選擇最大值的子流程,因此人們形象地稱之爲選擇排序。 app

舉個實例來看看: less

初始: [38, 17, 16, 16, 7, 31, 39, 32, 2, 11] ide

i = 0:  [2 , 17, 16, 16, 7, 31, 39, 32, 38 , 11] (0th [38]<->8th [2]) 工具

i = 1:  [2, 7 , 16, 16, 17 , 31, 39, 32, 38, 11] (1st [38]<->4th [17]) 測試

i = 2:  [2, 7, 11 , 16, 17, 31, 39, 32, 38, 16 ] (2nd [11]<->9th [16]) ui

i = 3:  [2, 7, 11, 16, 17, 31, 39, 32, 38, 16] ( 無需交換 ) this

i = 4:  [2, 7, 11, 16, 16 , 31, 39, 32, 38, 17 ] (4th [17]<->9th [16])

i = 5:  [2, 7, 11, 16, 16, 17 , 39, 32, 38, 31 ] (5th [31]<->9th [17])

i = 6:  [2, 7, 11, 16, 16, 17, 31 , 32, 38, 39 ] (6th [39]<->9th [31])

i = 7:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 無需交換 )

i = 8:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 無需交換 )

i = 9:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 無需交換 )

由例子能夠看出,選擇排序隨着排序的進行( i 逐漸增大),比較的次數會愈來愈少,可是不論數組初始是否有序,選擇排序都會從 i 至數組末尾進行一次選擇比較,因此給定長度的數組,選擇排序的比較次數是固定的: 1 + 2 + 3 + …. + n = n * (n + 1) / 2 ,而交換的次數則跟初始數組的順序有關,若是初始數組順序爲隨機,則在最壞狀況下,數組元素將會交換 n 次,最好的狀況下則可能 0 次(數組自己即爲有序)。

由此能夠推出,選擇排序的時間複雜度和空間複雜度分別爲 O(n2 ) O(1) (選擇排序只須要一個額外空間用於數組元素交換)。

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Selection Sorting  
  3.  */  
  4. SELECTION(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         int len = array.length;   
  7.         for (int i = 0; i < len; i++) {   
  8.             int selected = i;   
  9.             for (int j = i + 1; j < len; j++) {   
  10.                 int compare = array[j].compareTo(array[selected]);   
  11.                 if (compare != 0 && compare < 0 == ascend) {   
  12.                     selected = j;   
  13.                 }   
  14.             }   
  15.   
  16.             exchange(array, i, selected);   
  17.         }   
  18.     }   
  19. })  
/**
	 * Selection Sorting
	 */
	SELECTION(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int len = array.length;
			for (int i = 0; i < len; i++) {
				int selected = i;
				for (int j = i + 1; j < len; j++) {
					int compare = array[j].compareTo(array[selected]);
					if (compare != 0 && compare < 0 == ascend) {
						selected = j;
					}
				}

				exchange(array, i, selected);
			}
		}
	})

 

 

2. 插入排序

插入排序的基本思想是在遍歷數組的過程當中,假設在序號 i 以前的元素即 [0..i-1] 都已經排好序,本趟須要找到 i 對應的元素 x 的正確位置 k ,而且在尋找這個位置 k 的過程當中逐個將比較過的元素日後移一位,爲元素 x 「騰位置」,最後將 k 對應的元素值賦爲 x ,插入排序也是根據排序的特性來命名的。

如下是一個實例,紅色 標記的數字爲插入的數字,被劃掉的數字是未參與這次排序的元素,紅色 標記的數字與被劃掉數字之間的元素爲逐個向後移動的元素,好比第二趟參與排序的元素爲 [11, 31, 12] ,須要插入的元素爲 12 ,可是 12 當前並無處於正確的位置,因而咱們須要依次與前面的元素 31 11 作比較,一邊比較一邊移動比較過的元素,直到找到第一個比 12 小的元素 11 時中止比較,此時 31 對應的索引 1 則是 12 須要插入的位置。

初始:    [11, 31, 12, 5, 34, 30, 26, 38, 36, 18]

第一趟: [11, 31 , 12, 5, 34, 30, 26, 38, 36, 18] (無移動的元素)

第二趟: [11, 12 , 31, 5, 34, 30, 26, 38, 36, 18] 31 向後移動)

第三趟: [5 , 11, 12, 31, 34, 30, 26, 38, 36, 18] 11, 12, 31 皆向後移動)

第四趟: [5, 11, 12, 31, 34 , 30, 26, 38, 36, 18] (無移動的元素)

第五趟: [5, 11, 12, 30 , 31, 34, 26, 38, 36, 18] 31, 34 向後移動)

第六趟: [5, 11, 12, 26 , 30, 31, 34, 38, 36, 18] 30, 31, 34 向後移動)

第七趟: [5, 11, 12, 26, 30, 31, 34, 38 , 36, 18] (無移動的元素)

第八趟: [5, 11, 12, 26, 30, 31, 34, 36 , 38, 18] 38 向後移動)

第九趟: [5, 11, 12, 18 , 26, 30, 31, 34, 36, 38] 26, 30, 31, 34, 36, 38 向後移動)

插入排序會優於選擇排序,理由是它在排序過程當中可以利用前部分數組元素已經排好序的一個優點,有效地減小一些比較的次數,固然這種優點得看數組的初始順序如何,最壞的狀況下(給定的數組剛好爲倒序)插入排序須要比較和移動的次數將會等於 1 + 2 + 3… + n = n * (n + 1) / 2 ,這種極端狀況下,插入排序的效率甚至比選擇排序更差。所以插入排序是一個不穩定的排序方法,插入效率與數組初始順序息息相關。通常狀況下,插入排序的時間複雜度和空間複雜度分別爲 O(n2 ) O(1)

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Insertion Sorting  
  3.  */  
  4. INSERTION(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         int len = array.length;   
  7.         for (int i = 1; i < len; i++) {   
  8.             T toInsert = array[i];   
  9.             int j = i;   
  10.             for (; j > 0; j--) {   
  11.                 int compare = array[j - 1].compareTo(toInsert);   
  12.                 if (compare == 0 || compare < 0 == ascend) {   
  13.                     break;   
  14.                 }   
  15.                 array[j] = array[j - 1];   
  16.             }   
  17.   
  18.             array[j] = toInsert;   
  19.         }   
  20.     }   
  21. })  
/**
	 * Insertion Sorting
	 */
	INSERTION(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int len = array.length;
			for (int i = 1; i < len; i++) {
				T toInsert = array[i];
				int j = i;
				for (; j > 0; j--) {
					int compare = array[j - 1].compareTo(toInsert);
					if (compare == 0 || compare < 0 == ascend) {
						break;
					}
					array[j] = array[j - 1];
				}

				array[j] = toInsert;
			}
		}
	})

 

3. 冒泡排序

冒泡排序能夠算是最經典的排序算法了,記得小弟上學時最早接觸的也就是這個算法了,由於實現方法最簡單,兩層 for 循環,裏層循環中判斷相鄰兩個元素是否逆序,是的話將兩個元素交換,外層循環一次,就能將數組中剩下的元素中最小的元素「浮」到最前面,因此稱之爲冒泡排序。

照例舉個簡單的實例吧:

初始狀態:   [24, 19, 26, 39, 36, 7, 31, 29, 38, 23]

內層第一趟: [24, 19, 26, 39, 36, 7, 31, 29, 23 , 38 ] 9th [23]<->8th [38

內層第二趟: [24, 19, 26, 39, 36, 7, 31, 23 , 29 , 38] 8th [23]<->7th [29]

內層第三趟: [24, 19, 26, 39, 36, 7, 23 , 31 , 29, 38] 7th [23]<->6th [31]

內層第四趟: [24, 19, 26, 39, 36, 7, 23, 31, 29, 38] 7 23 都位於正確的順序,無需交換)

內層第五趟: [24, 19, 26, 39, 7 , 36 , 23, 31, 29, 38] 5th [7]<->4th [36]

內層第六趟: [24, 19, 26, 7 , 39 , 36, 23, 31, 29, 38] 4th [7]<->3rd [39]

內層第七趟: [24, 19, 7 , 26 , 39, 36, 23, 31, 29, 38] 3rd [7]<->2nd [26]

內層第八趟: [24, 7 , 19 , 26, 39, 36, 23, 31, 29, 38] 2nd [7]<->1st [19]

內層第九趟: [7 , 24 , 19, 26, 39, 36, 23, 31, 29, 38] 1st [7]<->0th [24]

…...

其實冒泡排序跟選擇排序比較相像,比較次數同樣,都爲 n * (n + 1) / 2 ,可是冒泡排序在挑選最小值的過程當中會進行額外的交換(冒泡排序在排序中只要發現相鄰元素的順序不對就會進行交換,與之對應的是選擇排序,只會在內層循環比較結束以後根據狀況決定是否進行交換),因此在我看來,選擇排序屬於冒泡排序的改進版。

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Bubble Sorting, it's very similar with Insertion Sorting  
  3.  */  
  4. BUBBLE(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         int length = array.length;   
  7.         int lastExchangedIdx = 0;   
  8.         for (int i = 0; i < length; i++) {   
  9.             // mark the flag to identity whether exchange happened to false   
  10.             boolean isExchanged = false;   
  11.             // last compare and exchange happened before reaching index i   
  12.             int currOrderedIdx = lastExchangedIdx > i ? lastExchangedIdx : i;   
  13.             for (int j = length - 1; j > currOrderedIdx; j--) {   
  14.                 int compare = array[j - 1].compareTo(array[j]);   
  15.                 if (compare != 0 && compare > 0 == ascend) {   
  16.                     exchange(array, j - 1, j);   
  17.                     isExchanged = true;   
  18.                     lastExchangedIdx = j;   
  19.                 }   
  20.             }   
  21.             // if no exchange happen means array is already in order   
  22.             if (isExchanged == false) {   
  23.                 break;   
  24.             }   
  25.         }   
  26.     }   
  27. })  
/**
	 * Bubble Sorting, it's very similar with Insertion Sorting
	 */
	BUBBLE(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int length = array.length;
			int lastExchangedIdx = 0;
			for (int i = 0; i < length; i++) {
				// mark the flag to identity whether exchange happened to false
				boolean isExchanged = false;
				// last compare and exchange happened before reaching index i
				int currOrderedIdx = lastExchangedIdx > i ? lastExchangedIdx : i;
				for (int j = length - 1; j > currOrderedIdx; j--) {
					int compare = array[j - 1].compareTo(array[j]);
					if (compare != 0 && compare > 0 == ascend) {
						exchange(array, j - 1, j);
						isExchanged = true;
						lastExchangedIdx = j;
					}
				}
				// if no exchange happen means array is already in order
				if (isExchanged == false) {
					break;
				}
			}
		}
	})

 

 

4. 希爾排序

希爾排序的誕生是因爲插入排序在處理大規模數組的時候會遇到須要移動太多元素的問題。希爾排序的思想是將一個大的數組「分而治之」,劃分爲若干個小的數組,以 gap 來劃分,好比數組 [1, 2, 3, 4, 5, 6, 7, 8] ,若是以 gap = 2 來劃分,能夠分爲 [1, 3, 5, 7] [2, 4, 6, 8] 兩個數組(對應的,如 gap = 3 ,則劃分的數組爲: [1, 4, 7] [2, 5, 8] [3, 6] )而後分別對劃分出來的數組進行插入排序,待各個子數組排序完畢以後再減少 gap 值重複進行以前的步驟,直至 gap = 1 ,即對整個數組進行插入排序,此時的數組已經基本上快排好序了,因此須要移動的元素會很小很小,解決了插入排序在處理大規模數組時較多移動次數的問題。

具體實例請參照插入排序。

希爾排序是插入排序的改進版,在數據量大的時候對效率的提高幫助很大,數據量小的時候建議直接使用插入排序就行了。

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Shell Sorting  
  3.  */  
  4. SHELL(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         int length = array.length;   
  7.         int gap = 1;   
  8.   
  9.         // use the most next to length / 3 as the first gap   
  10.         while (gap < length / 3) {   
  11.             gap = gap * 3 + 1;   
  12.         }   
  13.   
  14.         while (gap >= 1) {   
  15.             for (int i = gap; i < length; i++) {   
  16.                 T next = array[i];   
  17.                 int j = i;   
  18.                 while (j >= gap) {   
  19.                     int compare = array[j - gap].compareTo(next);   
  20.                     // already find its position   
  21.                     if (compare == 0 || compare < 0 == ascend) {   
  22.                         break;   
  23.                     }   
  24.   
  25.                     array[j] = array[j - gap];   
  26.                     j -= gap;   
  27.                 }   
  28.                 if (j != i) {   
  29.                     array[j] = next;   
  30.                 }   
  31.             }   
  32.             gap /= 3;   
  33.         }   
  34.   
  35.     }   
  36. })  
/**
	 * Shell Sorting
	 */
	SHELL(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int length = array.length;
			int gap = 1;

			// use the most next to length / 3 as the first gap
			while (gap < length / 3) {
				gap = gap * 3 + 1;
			}

			while (gap >= 1) {
				for (int i = gap; i < length; i++) {
					T next = array[i];
					int j = i;
					while (j >= gap) {
						int compare = array[j - gap].compareTo(next);
						// already find its position
						if (compare == 0 || compare < 0 == ascend) {
							break;
						}

						array[j] = array[j - gap];
						j -= gap;
					}
					if (j != i) {
						array[j] = next;
					}
				}
				gap /= 3;
			}

		}
	})

 

 

5. 歸併排序

歸併排序採用的是遞歸來實現,屬於「分而治之」,將目標數組從中間一分爲二,以後分別對這兩個數組進行排序,排序完畢以後再將排好序的兩個數組「歸併」到一塊兒,歸併排序最重要的也就是這個「歸併」的過程,歸併的過程當中須要額外的跟須要歸併的兩個數組長度一致的空間,好比須要規定的數組分別爲: [3, 6, 8, 11] [1, 3, 12, 15] (雖然邏輯上被劃爲爲兩個數組,但實際上這些元素仍是位於原來數組中的,只是經過一些 index 將其劃分紅兩個數組,原數組爲 [3, 6, 8, 11, 1, 3, 12, 15 ,咱們設置三個指針 lo, mid, high 分別爲 0,3,7 就能夠實現邏輯上的子數組劃分)那麼須要的額外數組的長度爲 4 + 4 = 8 。歸併的過程能夠簡要地歸納爲以下:

1) 將兩個子數組中的元素複製到新數組 copiedArray 中,之前面提到的例子爲例,則 copiedArray = [3, 6, 8, 11, 1, 3, 12, 15]

2) 設置兩個指針分別指向原子數組中對應的第一個元素,假定這兩個指針取名爲 leftIdx rightIdx ,則 leftIdx = 0 (對應 copiedArray 中的第一個元素 [3] ), rightIdx = 4 (對應 copiedArray 中的第五個元素 [1] );

3) 比較 leftIdx rightIdx 指向的數組元素值,選取其中較小的一個並將其值賦給原數組中對應的位置 i ,賦值完畢後分別對參與賦值的這兩個索引作自增 1 操做,若是 leftIdx rigthIdx 值已經達到對應數組的末尾,則餘下只須要將剩下數組的元素按順序 copy 到餘下的位置便可。

下面給個歸併的具體實例:

第一趟:

輔助數組 [21 , 28, 39 | 35, 38] (數組被拆分爲左右兩個子數組,以 | 分隔開)

[21 ,  ,  ,  ,  ] (第一次 21 35 比較 , 左邊子數組勝出, leftIdx = 0 i = 0

第二趟:

輔助數組 [21, 28 , 39 | 35, 38]

[21 , 28,  ,  ,  ] (第二次 28 35 比較,左邊子數組勝出, leftIdx = 1 i = 1

第三趟: [21, 28, 39 | 35 , 38]

 [21 , 28 , 35,  ,  ] (第三次 39 35 比較,右邊子數組勝出, rightIdx = 0 i = 2

第四趟: [21, 28, 39 | 35, 38 ]

 [21 , 28 , 35 , 38,  ] (第四次 39 38 比較,右邊子數組勝出, rightIdx = 1 i = 3

第五趟: [21, 28, 39 | 35, 38]

 [21 , 28 , 35 , 38 , 39] (第五次時右邊子數組已複製完,無需比較 leftIdx = 2 i = 4

以上即是一次歸併的過程,咱們能夠將整個須要排序的數組作有限次拆分(每次一分爲二)直到分爲長度爲 1 的小數組爲止,長度爲 1 時數組已經不用排序了。在這以後再逆序(因爲採用遞歸)依次對這些數組進行歸併操做,直到最後一次歸併長度爲 n / 2 的子數組,歸併完成以後數組排序也完成。

歸併排序須要的額外空間是全部排序中最多的,每次歸併須要與參與歸併的兩個數組長度之和相同個元素(爲了提供輔助數組)。則能夠推斷歸併排序的空間複雜度爲 1 + 2 + 4 + … + n = n * ( n + 2) / 4 (忽略了 n 的奇偶性的判斷),時間複雜度比較難估,這裏小弟也忘記是多少了(囧)。

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Merge sorting  
  3.  */  
  4. MERGE(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         this.sort(array, 0, array.length - 1, ascend);   
  7.     }   
  8.   
  9.     private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {   
  10.         // OPTIMIZE ONE   
  11.         // if the substring's length is less than 20,   
  12.         // use insertion sort to reduce recursive invocation   
  13.         if (hi - lo < 20) {   
  14.             for (int i = lo + 1; i <= hi; i++) {   
  15.                 T toInsert = array[i];   
  16.                 int j = i;   
  17.                 for (; j > lo; j--) {   
  18.                     int compare = array[j - 1].compareTo(toInsert);   
  19.                     if (compare == 0 || compare < 0 == ascend) {   
  20.                         break;   
  21.                     }   
  22.                     array[j] = array[j - 1];   
  23.                 }   
  24.   
  25.                 array[j] = toInsert;   
  26.             }   
  27.   
  28.             return;   
  29.         }   
  30.   
  31.         int mid = lo + (hi - lo) / 2;   
  32.         sort(array, lo, mid, ascend);   
  33.         sort(array, mid + 1, hi, ascend);   
  34.         merge(array, lo, mid, hi, ascend);   
  35.     }   
  36.   
  37.     private <T extends Comparable<T>> void merge(T[] array, int lo, int mid, int hi, boolean ascend) {   
  38.         // OPTIMIZE TWO   
  39.         // if it is already in right order, skip this merge   
  40.         // since there's no need to do so   
  41.         int leftEndCompareToRigthStart = array[mid].compareTo(array[mid + 1]);   
  42.         if (leftEndCompareToRigthStart == 0 || leftEndCompareToRigthStart < 0 == ascend) {   
  43.             return;   
  44.         }   
  45.   
  46.         @SuppressWarnings("unchecked")   
  47.         T[] arrayCopy = (T[]) new Comparable[hi - lo + 1];   
  48.         System.arraycopy(array, lo, arrayCopy, 0, arrayCopy.length);   
  49.   
  50.         int lowIdx = 0;   
  51.         int highIdx = mid - lo + 1;   
  52.   
  53.         for (int i = lo; i <= hi; i++) {   
  54.             if (lowIdx > mid - lo) {   
  55.                 // left sub array exhausted   
  56.                 array[i] = arrayCopy[highIdx++];   
  57.             } else if (highIdx > hi - lo) {   
  58.                 // right sub array exhausted   
  59.                 array[i] = arrayCopy[lowIdx++];   
  60.             } else if (arrayCopy[lowIdx].compareTo(arrayCopy[highIdx]) < 0 == ascend) {   
  61.                 array[i] = arrayCopy[lowIdx++];   
  62.             } else {   
  63.                 array[i] = arrayCopy[highIdx++];   
  64.             }   
  65.         }   
  66.     }   
  67. })  
/**
	 * Merge sorting
	 */
	MERGE(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			this.sort(array, 0, array.length - 1, ascend);
		}

		private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
			// OPTIMIZE ONE
			// if the substring's length is less than 20,
			// use insertion sort to reduce recursive invocation
			if (hi - lo < 20) {
				for (int i = lo + 1; i <= hi; i++) {
					T toInsert = array[i];
					int j = i;
					for (; j > lo; j--) {
						int compare = array[j - 1].compareTo(toInsert);
						if (compare == 0 || compare < 0 == ascend) {
							break;
						}
						array[j] = array[j - 1];
					}

					array[j] = toInsert;
				}

				return;
			}

			int mid = lo + (hi - lo) / 2;
			sort(array, lo, mid, ascend);
			sort(array, mid + 1, hi, ascend);
			merge(array, lo, mid, hi, ascend);
		}

		private <T extends Comparable<T>> void merge(T[] array, int lo, int mid, int hi, boolean ascend) {
			// OPTIMIZE TWO
			// if it is already in right order, skip this merge
			// since there's no need to do so
			int leftEndCompareToRigthStart = array[mid].compareTo(array[mid + 1]);
			if (leftEndCompareToRigthStart == 0 || leftEndCompareToRigthStart < 0 == ascend) {
				return;
			}

			@SuppressWarnings("unchecked")
			T[] arrayCopy = (T[]) new Comparable[hi - lo + 1];
			System.arraycopy(array, lo, arrayCopy, 0, arrayCopy.length);

			int lowIdx = 0;
			int highIdx = mid - lo + 1;

			for (int i = lo; i <= hi; i++) {
				if (lowIdx > mid - lo) {
					// left sub array exhausted
					array[i] = arrayCopy[highIdx++];
				} else if (highIdx > hi - lo) {
					// right sub array exhausted
					array[i] = arrayCopy[lowIdx++];
				} else if (arrayCopy[lowIdx].compareTo(arrayCopy[highIdx]) < 0 == ascend) {
					array[i] = arrayCopy[lowIdx++];
				} else {
					array[i] = arrayCopy[highIdx++];
				}
			}
		}
	})

 

6. 快速排序

快速排序也是用歸併方法實現的一個「分而治之」的排序算法,它的魅力之處在於它能在每次partition(排序算法的核心所在)都能爲一個數組元素肯定其排序最終正確位置(一次就定位準,下次循環就不考慮這個元素了)。

快速排序的partition操做按如下邏輯進行,假定本次排序的數組爲arr

1) 選擇一個元素(爲了簡單起見,就選擇本次partition的第一個元素,即arr[0])做爲基準元素,接下來的步驟會爲其肯定排序完成後最終的位置;

2) 1)  接下來須要遍歷[1…n-1]對應的數組元素以幫助找到arr[0]值(以v替代)對應的位置,定義i爲當前訪問數組的索引,lt爲值小於v的最大索引,gt爲值大於v的最小索引,那麼在遍歷過程當中,若是發現i指向的值與v相等,則將i值加1,繼續下一次比較;若是i指向的值比v小,則將ilt對應的元素進行交換,而後分別將兩個索引加1;若是i指向的值比v大,則將igt對應的元素進行交換,而後i自增,gt自減。循環遍歷完成(i > gt時結束)以後能夠保證[0…lt-1]對應的值都是比v小的,[lt..gt]之間的值都是與v相等的,[gt+1…n-1]對應的值都是比v大的。

3) 分別對[0…lt-1][gt+1…n-1]兩個子數組進行排序,如此遞歸,直至子子子數組的長度爲0

 

下面舉個partition的具體實例:

初始(i = 1, lt = 0, gt = 8):

       [41, 59, 43, 26, 63, 30, 29, 26, 42](須要肯定位置的爲0th[41]

第一趟(i = 1, lt = 0, gt = 8):

       [41, 42, 43, 26, 63, 30, 29, 26, 59]1st[59] > 411st[59]<->8th[42]gt--

第二趟(i = 1, lt = 0, gt = 7):

       [41, 26, 43, 26, 63, 30, 29, 42, 59]1st[42] > 411st[42]<->7th[26]gt--

第三趟(i = 1, lt = 0, gt = 6):

       [26, 41, 43, 26, 63, 30, 29, 42, 59]1st[26] < 41, 1st[26]<->0st[41]i++, lt++

第四趟(i = 2, lt = 1, gt = 6):

       [26, 41, 29, 26, 63, 30, 43, 42, 59]2nd[43] > 412nd[43]<->6th[29]gt--

第五趟(i = 2, lt = 1, gt = 5):

       [26, 29, 41, 26, 63, 30, 43, 42, 59]2nd[29] < 41, 2nd[29]<->1st[41]i++lt++

第六趟(i = 3, lt = 2, gt = 5):    

       [26, 29, 26, 41, 63, 30, 43, 42, 59]3rd[26] < 413rd[26]<->2nd[41]i++lt++

第七趟(i = 4, lt = 3, gt = 5):

       [26, 29, 26, 41, 30, 63, 43, 42, 59] 4th[63] > 414th[63]<->5th[30]gt--

第八趟(i = 4, lt = 3, gt = 4):    

       [26, 29, 26, 30, 41, 63, 43, 42, 59]4th[30] < 414th[30]<->3rd[41]i++lt++

 

能夠看出,在一次partition以後,以41爲分割線,41左側皆爲比它小的元素,41右側皆爲比它大或相等的元素(固然這個實例比較特殊,沒有出現和41相等的元素)。快速排序顧名思義就是排序速度很是快,後面我會放在我機器上跑各個排序方法的時間對比圖。值得一提的是JDK中在Arrays工具內中內置的sort方法就是接合插入排序和三路快速排序實現的,有興趣的同窗能夠看看JDK的源碼。

 

實現代碼:

 

Java代碼 複製代碼  收藏代碼
  1. /**  
  2.  * Quick Sorting  
  3.  */  
  4. QUICK(new Sortable() {   
  5.     public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {   
  6.         this.sort(array, 0, array.length - 1, ascend);   
  7.     }   
  8.   
  9.     private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {   
  10.         if (lo >= hi) {   
  11.             return;   
  12.         }   
  13.   
  14.         T toFinal = array[lo];   
  15.         int leftIdx = lo;   
  16.         int rightIdx = hi;   
  17.   
  18.         int i = lo + 1;   
  19.   
  20.         while (i <= rightIdx) {   
  21.             int compare = array[i].compareTo(toFinal);   
  22.             if (compare == 0) {   
  23.                 i++;   
  24.             } else if (compare < 0 == ascend) {   
  25.                 exchange(array, leftIdx++, i++);   
  26.             } else {   
  27.                 exchange(array, rightIdx--, i);   
  28.             }   
  29.         }   
  30.   
  31.         // partially sort left array and right array   
  32.         // no need to include the leftIdx-th to rightIdx-th elements   
  33.         // since they are already in its final position   
  34.         sort(array, lo, leftIdx - 1, ascend);   
  35.         sort(array, rightIdx + 1, hi, ascend);   
  36.     }   
  37. })  
/**
	 * Quick Sorting
	 */
	QUICK(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			this.sort(array, 0, array.length - 1, ascend);
		}

		private <T extends Comparable<T>> void sort(T[] array, int lo, int hi, boolean ascend) {
			if (lo >= hi) {
				return;
			}

			T toFinal = array[lo];
			int leftIdx = lo;
			int rightIdx = hi;

			int i = lo + 1;

			while (i <= rightIdx) {
				int compare = array[i].compareTo(toFinal);
				if (compare == 0) {
					i++;
				} else if (compare < 0 == ascend) {
					exchange(array, leftIdx++, i++);
				} else {
					exchange(array, rightIdx--, i);
				}
			}

			// partially sort left array and right array
			// no need to include the leftIdx-th to rightIdx-th elements
			// since they are already in its final position
			sort(array, lo, leftIdx - 1, ascend);
			sort(array, rightIdx + 1, hi, ascend);
		}
	})

 

 

若是你但願查看完整代碼,請移駕至個人GoogleCode查看,傳送門

這裏是我測試時的測試用例,利用了枚舉和策略模式的優點,切換排序算法時相對會比較容易。

 

如下爲經典排序算法在我機器上運行的耗時對比圖(測試用的隨機數組長度爲50000),直接截的測試用例的圖。

 

 

 

 鑑於有博友提到沒法訪問GoogleCode,我將項目工程以附件的方式上傳了,須要的博友請下載吧.

相關文章
相關標籤/搜索