Advertisement
Tobiahao

REKURENCJA_03

Mar 22nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | None | 0 0
  1. /*
  2. Jednym z algorytmów skonstruowanych przy pomocy metody dziel i zwyciężaj jest algorytm wyszukiwania binarnego. Zdefiniuje metodę rekurencyjną, która będzie implementowała ten algorytm. Zademonstruj jego działania w programie. Zdefiniuj w tym programie inne nierekurencyjne funkcje z parametrami, które będą potrzebne.
  3. */
  4.  
  5. #include <stdio.h>
  6. #define ARRAY_SIZE 50
  7.  
  8. void fill_array(int *array)
  9. {
  10.     for(int i = 0; i < ARRAY_SIZE; i++)
  11.         array[i] = i*2;
  12. }
  13.  
  14. void binary_search(int array[], int element, int low, int high)
  15. {
  16.     int mid = (low + high)/2;
  17.    
  18.     if(low > high){
  19.         printf("There is no '%d' number in array\n", element);
  20.         return;
  21.     }
  22.    
  23.     if(element == array[mid]){
  24.         printf("Number found at position: %d\n", mid+1);
  25.         return;
  26.     }
  27.     else if(element < array[mid]) binary_search(array, element, low, mid-1);
  28.     else binary_search(array, element, mid+1, high);
  29. }
  30.  
  31. int main(void)
  32. {
  33.     int array[ARRAY_SIZE];
  34.     fill_array(array);
  35.  
  36.     int low = 0;
  37.     int high = ARRAY_SIZE-1;
  38.    
  39.     binary_search(array, 10, low, high);
  40.    
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement