排序就是把一組資料元素,依某個鍵值重新排列成有序序列。依資料量與存放位置,可分為內部排序(資料全在記憶體中,適合規模不大的序列)與外部排序(資料量太大,過程中需要反覆存取外部儲存媒體)。
另一個關鍵性質是穩定性:若排序前有兩個相等元素 Ai = Aj 且 Ai 在前,排序後 Ai 仍須在 Aj 之前。穩定性看似雞肋,實際上很有用——基數排序正是靠「先排低位、再排高位」的穩定特性運作;而對以比較為基礎的排序來說,穩定通常也意味著較少的元素交換。
把序列的第一個元素視為已排序的子序列,接著從第二個元素開始,每次取出一個,往後掃描已排序區找出合適位置插入,直到全部處理完畢。它對「近乎有序」的資料表現極佳。
哨兵(sentinel)元素有兩個作用:一是暫存待插入的元素,二是避免索引越界。當待插入元素比已排序區最小值還小時,j 會一路遞減到 -1 而越界;有了哨兵,arr[0] < arr[j] 在 j = 0 時自然成立、迴圈結束,不必每次判斷邊界(for 迴圈只需一次條件判斷,效率更好)。
但哨兵版有個必須注意的副作用:若傳進來的是原始陣列,插入第一個元素時 a[0] 會被覆寫,最終結果就少了原始的第一個元素。解法是在呼叫前先把陣列整體右移一格,第 0 格留給哨兵(初始化為 0 或留空皆可)。
/**
* 帶哨兵
*/
public static void insertSort1(Integer[] sortList) {
int len = sortList.length;
for (int i = 2; i < len; i++) {
if (sortList[i] < sortList[i - 1]) {
int j = i - 1;
sortList[0] = sortList[i];// 設置哨兵
while (sortList[0] < sortList[j]) {
sortList[j + 1] = sortList[j];
j--;
}
sortList[j + 1] = sortList[0];
}
}
}
/**
* 不帶哨兵
*/
public static void insertSort2(Integer[] sortList) {
int len = sortList.length;
for (int i = 1; i < len; i++) {
if (sortList[i] < sortList[i - 1]) {
int j = i - 1;
int temp = sortList[i];
while (j >= 0 && temp < sortList[j]) {
sortList[j + 1] = sortList[j];
j--;
}
sortList[j + 1] = temp;
}
}
}
耗時操作只有兩種:比較與後移賦值。
在有序區尋找插入位置時改用二分查找,可以減少比較次數:
public static void insertSort3(Integer[] sortList) {
int len = sortList.length;
for (int i = 1; i < len; i++) {
if (sortList[i] < sortList[i - 1]) {
// 二分查找在有序區尋找插入位置
int index = binarySearchIndex(sortList, i - 1, sortList[i]);
if (i != index) {
int temp = sortList[i];
// 後移元素,騰出 index 位置
for (int j = i - 1; j >= index; j--)
sortList[j + 1] = sortList[j];
sortList[index] = temp;
}
}
}
}
private static int binarySearchIndex(Integer[] sortList, int maxIndex, int data) {
int iBegin = 0;
int iEnd = maxIndex;
while (iBegin <= iEnd) {
int middle = (iBegin + iEnd) / 2;
if (sortList[middle] > data) {
iEnd = middle - 1;
} else {
iBegin = middle + 1;// 相同元素插入在後方,以維持穩定
}
}
return iBegin;
}
注意這裡找的不是「相等值」,而是插入位置,因此必須一路查到最後才確定歸屬。二分查找的比較次數為 log₂n,但後移賦值的量並未減少:最好情況 O(log₂n),最壞情況仍是 n(n-1)/2 加上 n-1 次,平均 O(n²),空間 O(1),且依然穩定。
結論很實用:二分查找插入排序省的是「比較」,不是「搬移」。當比較成本遠高於賦值(例如元素比較昂貴)時收益明顯,否則提升有限。