码迷,mamicode.com
首页 > 其他好文 > 详细

折半查找

时间:2015-06-07 11:11:08      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:c-c++   数据结构   查找算法   

折半查找

// 折半查找.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");
}

技术分享

折半查找

标签:c-c++   数据结构   查找算法   

原文地址:http://blog.csdn.net/u011233535/article/details/46398287

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!