1. 程式人生 > >二分插入排序演算法的C/C++實現

二分插入排序演算法的C/C++實現

#include<stdio.h>

/*
  Name: 
  Copyright: 
  Author: @dujianjian 
  Date: 26/10/12 12:41
  Description: 二分插入排序 
*/
void binary_insert_sort(int a[],int n){
     for(int i =1;i<n;i++){
             int temp = a[i];
             int low  = 0 ;
             int high = i;
             //二分查詢插入位置 
             while(low <= high){
                              int mid = (low + high) >> 1; 
                              if(temp > a[mid])low = mid + 1;
                              else high = mid - 1; 
                              } 
             //向後移動資料 
             for(int j = i - 1;j >= high + 1;j--)a[j+1] = a[j];
             
             a[high+1] = temp; //插入 
             } 
     } 
int main(){
    int a[10] = {5,9,8,7,2,6,1,0,3,4};
    
    for(int i = 0;i<10;i++)
     printf("%d ",a[i]);
     printf("\n");
      
     binary_insert_sort( a, 10);
      
     for(int i = 0;i<10;i++)
     printf("%d ",a[i]);
     printf("\n");
     getchar(); 
    return 0; 
    } 

示例結果: