1. 程式人生 > >演算法 c語言 折半排序演算法

演算法 c語言 折半排序演算法

#include<stdio.h>
#define N 8
void binsearch(int a[]);
void show(int a[]);
int main()
{    
    
    int a[N] = {50,36,66,76,95,12,25,36};
    printf("原無序記錄:\n");
    show(a);
    printf("排序過程如下\n");
    binsearch(a);
    return 0;
}
void show(int a[])
{
    int i;
    for(i = 0;i < N;i++)
    {
        printf("%d\t",a[i]);
    }
    puts("");
}
void binsearch(int a[])
{
    int i,j,tmp,low,high,mid;
    for(i = 1;i < N;i++)
    {
        tmp = a[i];//無序記錄儲存temp中 有序記錄中折半查詢插入位置
        for(low = 0,high = i -1;low <= high;)
        {
            mid = (low + high)/2;
            if(tmp < a[mid])
                high = mid -1;
            else
                low = mid + 1;
        }
        //將從low開始的有序記錄向後移動一個位置
        for(j = i;j > low;j--)
        {
            a[j] = a[j - 1];
        }
        a[low] = tmp;
        show(a);
    }
}