// // main.c // 折半查找 // // Created by wangpeng on 15/6/26. // Copyright (c) 2015年 wangpeng. All rights reserved. //
#include <stdio.h>
/* 折半查找的函数 */ int findNum(int arr[],int len,int key){ int low=0,high=len-1,mid; while (low<=high) { mid = (low+high)/2; printf("mid = %d\n",mid); if (key>arr[mid]) { low = mid+1; }else if (key<arr[mid]){ high = mid - 1; }else{ return mid; } } // 下面是查找不到的情况 return -1; }
int main(int argc, const char * argv[]) { int len; printf("len:\n"); scanf("%d",&len);//输入长度 int arr[len],num; for (int i=0; i<len; i++) {//输入数组元素 printf("No.%d:\n",i); scanf("%d",&num); arr=num; } printf("\narr:\n"); for (int i=0; i<len; i++) {//查看原始数组 printf("%d\t",arr); } int temp; for (int i=0; i<len-1; i++) {//排序 for (int j=i+1; j<len; j++) { if (arr>arr[j]) { temp=arr; arr=arr[j]; arr[j]=temp; } } } printf("\nnew arr:\n"); for (int i=0; i<len; i++) {//查看新数组 printf("%d\t",arr); } int key; printf("\nkey:\n"); scanf("%d",&key);//输入key
printf("arr[%d]\n",findNum(arr, len, key));//调用函数查找 return 0; }
|