二分查找的递归算法程序

#include<iostream>
using namespace std;

int search_sorted(int a[], int p, int q, int v);

int main()
{
 int size;

 cout << “input the size of th array: ” << endl;
 cin >> size;

 int *pa = new int [size];
 cout << “input the ” << size << ” elements of array” << endl;
 for(int i = 0; i < size; i++)
 {
  cin >> pa[i]; 
 }

 cout << “input the value which you want to search:”;
 int value;
 cin >> value;

 int position = -1;
 position = search_sorted(pa, 0, size – 1, value);

 if (position > -1)
 {
  cout << “the position of the value in array is: ” << position + 1 << endl; 
 }
 else
 {
  cout << “The value you want to search is not in the array.” << endl; 
 }

 return 0;
}
int search_sorted(int a[], int p, int q, int v)
{
 if (q >= p)
 {
  int mid = (q + p) / 2;

  if (a[mid] == v)
  {
   return mid;  
  }
  else if(a[mid] > v)
  {
   search_sorted(a,mid+1,q,v);  
  }
  else
  {
   search_sorted(a,p,mid-1,v);  
  }
 }
 else
 {
  return -1; 
 }
}

    原文作者:递归算法
    原文地址: https://blog.csdn.net/zoezinsser/article/details/535113
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞