1. 程式人生 > >二分插入排序 和 二分檢索

二分插入排序 和 二分檢索

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 10
#define sortObject int*

void binarySort(sortObject array)
{
 int mid, left, right, temp, i, j;
 for(i = 1; i < N; i++)
 { 
  left = 0;
  right = i - 1;
  temp = array[i];
  while(left <= right)
  { 
   mid = (left + right) / 2;
   if(temp < array[mid])
    right = mid - 1;
   else
    left = mid + 1;
  }
  
  for(j = i - 1; j >= left; j--)
   array[j + 1] = array[j];
  
  if(i != left)
   array[left] = temp;
 }
}

int binarySearch(int *array, int* postion, int key)
{
 int mid, left, right, temp;
 left = 0;
 right = N - 1;
 while(left <= right)
 {
  mid = (left + right) / 2; 
  
  if(array[mid] == key)
  {
   *postion = mid;
   return 1;
  }
  else if(key < array[mid])
   right = mid - 1;
  else
    left = mid + 1;
 }
 
 *postion = left;
 return 0;
}
int main(int argc, char ** argv)
{
 int a[] = {33, 14, 35, 21, 42, 66, 38, 67, 10, 79};
 binarySort(a);
 int i;
 for(i = 0; i < N; i++)
 {
  printf("%d ", a[i]);
 }
 printf("/n");
 char *s;
 int n = atoi(gets(s));
 int* postion = (int *)malloc(sizeof(int));
 binarySearch(a, postion, n);
 printf("%d/n", *postion); 
 return 0;
}