CPP 13
Binary-search.cpp Guest on 5th April 2021 10:47:19 AM
  1. /*
  2.  * binary-search.cpp
  3.  *
  4.  *  Created on: 23 Aug
  5.  *      Author: lucascordeiro
  6.  */
  7.  
  8. #include <assert.h>
  9.  
  10. int BinarySearch(int A[], int first, int last, int key)
  11. {
  12.     if (A[first]==key) return first;
  13.     else if (A[last]==key) return last;
  14.     else if ((last-first)==1 || (last-first)==0) return -1;
  15.  
  16.     int k=((first+last)/2);
  17.     if (key<A[k]) BinarySearch(A,0,(k-1),key);
  18.     else BinarySearch(A,k,last,key);
  19. }
  20. int main()
  21. {
  22.     int A[]={1,3,4};
  23.     int n=3, key=3;
  24.  
  25.     assert(BinarySearch(A,0,n-1,key)==1);
  26.     return 0;
  27. }

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.