标签:
// // main.c // BinarySearchDemo // // Created by zhanggui on 15/7/19. // Copyright (c) 2015年 zhanggui. All rights reserved. // #include <stdio.h> #include <time.h> #define N 20 int BinarySearch(int a[], int n,int found) { int low = 0; int high = n-1; int mid; // time_t startTime,endTime; //用于计算运行时间 // startTime = clock(); while (low <= high) { mid = (low+high)/2; if (found==a[mid]) { printf("-------------------\n"); // endTime = clock(); // double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC; // printf("花费时间为:%f",Total_Waste_Time); return mid; }else if (found<a[mid]) { high = mid - 1; }else { low = mid+1; } } // endTime = clock(); // double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC; // printf("花费时间为:%f",Total_Waste_Time); return -1; } int main(int argc, const char * argv[]) { int found; int a[N] = {3,4,5,6,7,8,9,10,14,15,18,20,31,43,56,67,84,90,92,96}; printf("请输入一个数:"); scanf("%d",&found); int i = BinarySearch(a, N, found); if (i != -1) { printf("在数组中的位置是%d\n",i); }else { printf("没有找到"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zhanggui/p/4658393.html