<Search algorithm> binary search BinarySearch

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int BinarySearch(int arr[],int begin,int end,int num)
 5 {
 6     if(arr == NULL || begin < 0 || end < 0 || begin >= end) return -1;
 7 
 8     int mid = (begin+end)/2;
 9     if(arr[mid] == num) 
10         return mid;
11     else if(arr[mid] > num)
12         BinarySearch(arr,begin,mid-1,num);
13     else if(arr[mid] < num)
14         BinarySearch(arr,mid+1,end,num);
15 }
16 
17 int main()
18 {
19     int arr[] = {2,4,11,13,20,24,33,56,78,91};
20     cout << "Found num index in the array is: " << the BinarySearch (ARR, 0 , the sizeof (ARR) / the sizeof (ARR [ 0 ]) - . 1 , 78 );
 21 is  
22 is      System ( " PAUSE " );
 23 is      return  0 ;
 24 }

 

Guess you like

Origin www.cnblogs.com/Aaaaaalei0612/p/11221011.html