zoukankan      html  css  js  c++  java
  • 二进制搜索

    二进制搜索

    // 二进制搜索.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("
    <<Binary search>>
    ");
        printf("
    Sorted data:");
        for (i = 1; i < 11; i++)
            printf("%d ",data[i]);
        puts("");
        printf("
    Please enter a number from data:");
        scanf("%d",&input);
        printf("
    Search......
    ");
        m = (t + n) / 2;                //键值在第M个上
        while (t <= n&&ok == 0)
        {
            printf("
    Data 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("
    
    Found,%d is the %dth record in data!",input,m);
                ok = 1;
            }
            m = (t+n)/ 2;
        }
        if (ok == 0)
            printf("
    
    Sorry,%d not found!",input);
        printf("
    ");
        system("pause");
    }
    
    

    測试1:

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

  • 相关阅读:
    为函数的参数指定类型
    装饰器函数导致的原函数的元数据被替代--保存元数据
    ssm单项目整合
    security权限控制
    springAOP学习笔记
    springIOC学习笔记
    springDataJpa学习笔记
    springmvc学习笔记
    原生mybaits学习笔记
    java反射和注解
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4812151.html
Copyright © 2011-2022 走看看