zoukankan      html  css  js  c++  java
  • 二叉搜索的应用

    代码
    //
    // binary_search.cpp
    //
    // Demo program of binary search.


    #include
    <stdio.h> // uses printf
    #include <stdlib.h>
    #include
    <algorithm>
    using namespace std;
    int binary_search(int data[],int search_item,int length)
    {
    int min =-1;
    int max = length;
    while(true)
    {
    // found condition.
    if(data[(min+max)/2]==search_item)
    return (min+max)/2;
    // termination condition.
    if(min==max)
    {
    return -1;
    }
    // else
    if(data[(min+max)/2]<search_item)
    {
    min
    =(min+max)/2;
    }
    else
    {
    max
    =(min+max)/2;
    }

    }
    }


    int main()
    {
    #define MAX_ARRAY_SIZE 100
    // an array to binary_search.
    int int_array[MAX_ARRAY_SIZE];

    // fill this array from the stdin.
    int count=0;
    printf(
    "please enter the numbers you want to sort -1 to end:\n");
    while(true)
    {
    int input;
    scanf(
    "%i",&input);

    if(input==-1)
    break;
    else
    int_array[count]
    =input;
    if(count>=MAX_ARRAY_SIZE)
    exit(
    0);
    ++count;
    }

    sort(int_array,int_array
    +count);
    printf(
    "\nAfter sort, the int_array is: ");
    for (int i = 0; i < count; ++i)
    {
    printf(
    "%4d",int_array[i]);
    }
    // get the value that you need to search.
    int search;
    printf(
    "\nPlese enter the value that you need to Search ");
    scanf(
    "%i",&search);

    // search.
    int result;
    if((result=binary_search(int_array,search,count))==-1)
    {
    printf(
    "the value %i does not found in the array\n",search);
    }
    else
    {
    printf(
    "the value %i is located at index %i\n",search,result);
    }

    return 0;
    }

  • 相关阅读:
    Postman之token动态获取
    AJAX省市县三级联动的实现
    Javamail简单使用案例
    JavaWeb之JSP入门
    js小例子之二级联动
    git常用命令
    centos下安装pip-python
    Pyspider抓取静态页面
    Python中__init__()方法注意点
    2、Pyspider使用入门
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/1924974.html
Copyright © 2011-2022 走看看