Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- */
- #include <stdio.h>
- #define ARRAY_SIZE 50
- void fill_array(int *array)
- {
- for(int i = 0; i < ARRAY_SIZE; i++)
- array[i] = i*2;
- }
- void binary_search(int array[], int element, int low, int high)
- {
- int mid = (low + high)/2;
- if(low > high){
- printf("There is no '%d' number in array\n", element);
- return;
- }
- if(element == array[mid]){
- printf("Number found at position: %d\n", mid+1);
- return;
- }
- else if(element < array[mid]) binary_search(array, element, low, mid-1);
- else binary_search(array, element, mid+1, high);
- }
- int main(void)
- {
- int array[ARRAY_SIZE];
- fill_array(array);
- int low = 0;
- int high = ARRAY_SIZE-1;
- binary_search(array, 10, low, high);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement