折半插入排序

折半插入排序(binary insertion sort)是对插入排序算法的一种改进,由于排序算法过程中,就是不断的依次将元素插入前面已排好序的序列中。由于前半部分为已排好序的数列,这样我们不用按顺序依次寻找插入点,可以采用折半查找的方法来加快寻找插入点的速度。

基本思想:

折半插入排序算法的具体操作为:在将一个新元素插入已排好序的数组的过程中,寻找插入点时,将待插入区域的首元素设置为a[low],末元素设置为a[high],则轮比较时将待插入元素与a[m],其中m=(low+high)/2相比较,如果比参考元素小,则选择a[low]a[m-1]为新的插入区域(high=m-1),否则选择a[m+1]a[high]为新的插入区域(即low=m+1),如此直至low<=high不成立,即将此位置之后所有元素后移一位,并将新元素插入a[high+1]

时间性能

比直接插入算法明显减少了关键字之间比较的次数,因此速度比直接插入排序算法快,但记录移动的次数没有变,所以折半插入排序算法的时间复杂度仍然为O(n^2),与直接插入排序算法相同

稳定性

    稳定

    

public class BinaryInsertionSort {

	public static void binaryInsertSort(int a[], int left, int right) {
		
		for (int i = left + 1; i <= right; i++) {
			int temp = a[i];
			int low = left;
			int high = i - 1;
			while (low <= high) {
				int mid = (low + high) / 2;
				if (temp < a[mid])
					high = mid - 1;
				else
					low = mid + 1;
			}
			for (int j = i - 1; j >= low; j--)
			{
				a[j + 1] = a[j];
			}
			
			a[low] = temp;
		}
	}

	public static void main(String[] args) {

		int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 };

		System.out.print("排序前: ");
		for (int i = 0; i < a.length; i++)
			System.out.printf("%3s ", a[i]);
		System.out.println("");

		// 进行排序
		binaryInsertSort( a, 0, a.length-1 );;

		// 排序后结果
		System.out.print("排序后: ");
		for (int i = 0; i < a.length; i++)
			System.out.printf("%3s ", a[i]);
		System.out.println("");
	}
}

 

   

猜你喜欢

转载自lizhao6210-126-com.iteye.com/blog/1830086