author : neumanndong
date : 2017/4/9 11:06
折半插入排序(Binary Insertion Sort):插入排序的”查找“操作可以利用“折半查找”来实现,由此进行的插入排序称之为折半插入排序。
c实现:
void BInsertSort (SqList &L) { for (i = 2; i < L.length; ++i) { L.r[0] = L.r[i]; low = 1; high = i - 1; while (low < high) { int m = (low + high) / 2; if (LT(L.r[0].key, L.r[m].key)) high = m - 1; else low = m + 1; } for (int j = i - 1; j >= high + 1; --j) L.r[j + 1] = L.r[0]; } } }
Java实现:public class Test { public static void BInsertSort(int[] SqList) { for (int i = 1; i < SqList.length; ++i) { int low = 0; int high = i - 1; int temp = SqList[i]; while (low <= high) { int middle = (low + high) / 2; if (temp > SqList[middle]) low = middle + 1; else high = middle - 1; } int j; for (j = i - 1; j >= high + 1; --j) SqList[j + 1] = SqList[j]; SqList[j + 1] = temp; } } public static void main(String[] args) { int arr[] = { 49, 38, 65, 97, 76, 13, 27, 49 }; BInsertSort(arr); System.out.println("\n排序之后:"); for (int element : arr) { System.out.print(element + " "); } } }
Python 实现:
def BInsertSort(SqList): length = len(SqList) for i in range(1,length): low = 0 high = i temp = SqList[high] while ( low < high): middle = (low + high) // 2 if (temp > SqList[middle]): low = middle + 1 else: high = middle - 1 j = i - 1 while (j >= high + 1): SqList[j + 1] = SqList[j]; j = j - 1; SqList[j+ 1] = temp if __name__ == "__main__": SqList = [49, 38, 65, 97, 76, 13, 27, 49] BInsertSort(SqList) for i in SqList: print i
非稳定时间复杂度 O(n*n) 记录的移动次数不变,关键字比较次数减少
******************************************
I guess it comes down to a simple choice:get busy living or get busy dying.
生命可以归结为一种简单的选择:要么忙于生存,要么赶着去死