二分查找算法

//
//  BinarySearch.c
//  libin
//
//  Created by 李宾 on 16/4/28.
//  Copyright © 2016年 李宾. All rights reserved.
//

#include <stdio.h>
//非递归
int Binary_Search(int a[], int low, int high, int key)
{
    while (low <= high)
    {
        int mid = (low + high)/2;
        if(a[mid] == key)
        {
            return mid;
        }
        else if(a[mid] < key)
        {
            low = mid + 1;
        }
        else
            high = mid - 1;
    }
return -1; } //递归 int Binary_Search1(int a[], int low, int high, int key) {
  if(low > high)
  {
    return -1;
  }
int mid = (low + high)/2;

  if (a[mid] == key )
  {
return mid; } else if(a[mid] < key) { return Binary_Search1(a, mid+1, high, key); } else return Binary_Search1(a, mid, high-1, key); } } int main() { int a[6] = {1, 23, 33, 45, 56, 65}; Binary_Search1(a, 0, 5, 34); }

 

posted @ 2016-04-28 20:39  32ddd  阅读(152)  评论(0编辑  收藏  举报