您的位置:首页 > 其它

排序算法(五)二分排序

2015-08-24 16:01 232 查看
二分排序是指折半插入排序。当直接插入排序进行到某一趟时,对于r[i].key来讲,前边i-1个记录已经按关键字有序。此时不用直接插入排序的方法,而改为二分折半查找,找出r[i].key应插入的位置,然后插入。

Java实现二分排序算法:

package com.review.sort;

public class BinarySort {

public static void main(String[] args) {

int[] a = { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
int i, j;
int low, high, mid;
int temp;
for (i = 1; i < a.length; i++) {
temp = a[i];
low = 0;
high = i - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > temp)
high = mid - 1;
else
low = mid + 1;
}
for (j = i - 1; j > high; j--)
a[j + 1] = a[j];
a[high + 1] = temp;

}

for (i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}

}


算法分析:

二分排序中,关键字的比较次数由于采用了折半查找而减少,数量级为O(n log n),但是元素移动次数仍为O(n^2)。故折半插入排序时间复杂度仍未O(n^2)。二分排序方法是稳定的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: