排序算法之折半插入排序的思想以及Java实现

1 基本思想
折半插入排序(binary insertion sort)的基本原理与直接插入排序相同,不同之处在于,确定当前记录在前面有序子数组中的位置时,直接插入排序是采用顺序查找的方法,而折半插入排序是采用折半查找的方法,因此它仅适用于顺序存储的线性表。

2,算法的实现(Java)

package Algorithm;

public class binary_insert_sort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int array[] = {23,12,34,56,78,67,99,100};
         System.out.println("---------排序前的结果----------");  
         binary_insert_sort.output(array);
         System.out.println("---------排序后的结果----------");  
         binary_insert_sort.binary_insert_sort(array);
         binary_insert_sort.output(array);
    }
   //折半插入排序算法
    public static void  binary_insert_sort(int[] arr){
        int low,high,mid,temp,j;
        for(int i=1;i<arr.length;i++){
            temp = arr[i];
            low = 0;
            high = i-1;
            while(low <=high){
                mid =(high+low)/2;
                if(arr[mid] > temp){
                    high = mid -1;
                }
                else
                {
                    low = mid+1;
                }
            }
                for(j = i-1;j >=high+1; j--)
                    arr[j+1] = arr[j];
                arr[j+1] = temp;
        }

    }
    //输出打印
        public static void output(int[] arr){
            for(int i=0;i<arr.length;i++){
                System.out.print(arr[i]+",");
            }
            System.out.println();
        }

}

得到的结果如下所示:
这里写图片描述
3,性能分析
折半查找只是减少了比较次数,但是元素的移动次数不变。因此,它的
空间复杂度 O(1) ,时间复杂度O(n^2),是一种稳定的排序算法

原文地址:https://www.cnblogs.com/cmderq/p/9130857.html