折半插入排序

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. 

生命可以归结为一种简单的选择:要么忙于生存,要么赶着去死







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值