Ctyderv

Untitled

Jun 11th, 2021
717
4 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2.  
  3. int bsearch( int k, int vec[], int lo, int hi, int x) {
  4.     while( lo <= hi) {
  5.         int mid = lo + ( hi - lo) / 2;
  6.         //printf( "%d %d %d\n",lo, hi, mid);
  7.         if( vec[mid] == x) return mid;
  8.  
  9.         if(k == vec[mid] < x) lo = mid + 1;
  10.             else hi = mid - 1;
  11.     }
  12.  
  13.     return -1;
  14. }
  15.  
  16. int search( int vec[], int len, int x) {
  17.     int s1 = bsearch( 1, vec, 0, len / 2 - 1, x);
  18.     int s2 = bsearch( 0, vec, len / 2, len - 1, x);
  19.  
  20.     if( s1 != -1) return s1;
  21.     return s2;
  22. }
  23.  
  24. int main() {
  25.     int test[] = { 1, 3, 5, 7, 9, 8, 6, 4, 2, 0};
  26.     int n = sizeof( test) / sizeof( int);
  27.  
  28.     for( int i = 0; i < 15; i++)
  29.         printf( "%d\n", search( test, n, i));
  30.  
  31. }
RAW Paste Data