zoukankan      html  css  js  c++  java
  • 基于递归的折半查找

     

    请编写一个递归的折半查找算法,查找给定有序数组中的某一元素。

    多组数据,每组数据有三行。第一行为数组长度n,第二行为n个递增排列的数字,第三行为需要查找的数字k。当n=0时输入结束。

    每组数据输出一行,如果可以找到数字,则输出“YES”,否则输出“NO”。

    5
    1 4 6 7 8
    6
    6
    1 2 5 7 9 100
    8
    0
    
    YES
    NO

     1 #include<iostream>
     2 using namespace std;
     3 
     4 bool binary_search(int arr[], int low, int high, int target)
     5 {
     6     if (low > high)
     7         return false;
     8     if (low <= high)
     9     {
    10         int mid = (low + high) / 2;
    11         if (arr[mid] == target)
    12             return true;
    13         else if (mid < target)
    14         {
    15             binary_search(arr, mid + 1, high, target);
    16         }
    17         else
    18         {
    19             binary_search(arr, low, mid - 1, target);
    20         }
    21     }
    22 }
    23 
    24 int main()
    25 {
    26     int *arr;
    27     int n, target;
    28     while (cin >> n)
    29     {
    30         if (n == 0) break;
    31         arr = new int[n + 1];
    32         for (int i = 1; i <= n; i++)
    33             cin >> arr[i];
    34 
    35         cin >> target;
    36         bool flag = binary_search(arr, 1, n, target);
    37         if (flag)
    38             cout << "YES" << endl;
    39         else
    40             cout << "NO" << endl;
    41         delete[]arr;
    42     }
    43     return 0;
    44 }
  • 相关阅读:
    学习中的坑
    友链
    CF1131E String Multiplication 题解
    CF438E The Child and Binary Tree 题解
    [WC2005]友好的生物题解
    [IOI2016]shortcut 题解
    CF911F [Tree Destruction] 题解
    状压dp技巧之轮廓线 hdu1400/poj2411acwing291 蒙德里安的梦想
    TG-WC2021 笔记
    拯救世界2题解
  • 原文地址:https://www.cnblogs.com/christy99cc/p/10116718.html
Copyright © 2011-2022 走看看