首页 > 编程语言 > 详细

C语言 -- 折半查找小程序

时间:2016-01-19 22:14:20      阅读:191      评论:0      收藏:0      [点我收藏+]


#include <stdio.h>

int searchNum(int *arr, int num, int len);

int main(int argc, const char * argv[]) {
    
    int a[9] = {3, 0, -5, 88, 99, 100, -10, 50, 20};
    int i = 0, j = 0;
    int num;
    printf("please input a number: \n");
    scanf("%d", &num);
    int temp;
    int length = sizeof(a) / sizeof(a[0]);
    for(; i < length; i++){
        for(j = i + 1; j < length; j++){
            if(a[i] > a[j]){
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    
    int res = searchNum(a, num, length);
    
    if(res != -1){
        printf("Find it.\n");
    }else{
        printf("Not found.\n");
    }
    
    return 0;
}

int searchNum(int *arr, int num, int len){
    int max = len-1, min = 0;
    int mid = (max + min) * 0.5;
    while(num != arr[mid]){
        if(num > arr[mid]){
            min = mid + 1;
        }else if(num < arr[mid]){
            max = mid - 1;
        }
        if(min > max){
            return -1;
        }
        mid = (max + min) * 0.5;
    }
    return mid;
    
}

C语言 -- 折半查找小程序

原文:http://www.cnblogs.com/lianfu/p/5143556.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!