折半查找

来源:互联网 发布:js或 编辑:程序博客网 时间:2024/05/29 17:31

折半查找

// 折半查找.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:

0 0
原创粉丝点击