二进制搜索

二进制搜索

// 二进制搜索.cpp : 自定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<stdio.h>
#include<windows.h>

void main()
{
    int data[11] = {0,12,23,29,38,44,57,64,75,82,98};
    int i, t = 1, n = 10, m, cnt = 0, input, ok = 0;
    printf("\n<<Binary search>>\n");
    printf("\nSorted data:");
    for (i = 1; i < 11; i++)
        printf("%d ",data[i]);
    puts("");
    printf("\nPlease enter a number from data:");
    scanf("%d",&input);
    printf("\nSearch......\n");
    m = (t + n) / 2;                //键值在第M个上
    while (t <= n&&ok == 0)
    {
        printf("\nData when searching %2d time(s) is %d !",++cnt,data[m]);
        if (data[m]>input)//要查找的数据小于键值,则数据在键值的前面
        {
            n=m - 1;
            printf("--->Choice number is smaller than %d",data[m]);
        }
        else                     //否则数据在键值的后面
        if (data[m] < input)
        {
            t = m + 1;
            printf("--->Choice number is bigger than %d",data[m]);
        }
        else
        {
            printf("\n\nFound,%d is the %dth record in data!",input,m);
            ok = 1;
        }
        m = (t+n)/ 2;
    }
    if (ok == 0)
        printf("\n\nSorry,%d not found!",input);
    printf("\n");
    system("pause");
}

測试1:

版权声明:本文博主原创文章,欢迎大家分享和纠正。

posted @ 2015-09-16 08:55  zfyouxi  阅读(183)  评论(0编辑  收藏  举报