Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define LEN 16
- bool binary_search(int v[], size_t length, int to_find);
- int main(void) {
- int vtest[LEN];
- srand(time(NULL));
- for (size_t i = 0; i < LEN; i++) {
- vtest[i] = rand() % 30 + 1;
- }
- // Simple sorting implementation
- for (size_t i = 0; i < LEN; i++) {
- for (size_t j = i + 1; j < LEN; j++) {
- if (vtest[i] > vtest[j]) {
- int temp = vtest[i];
- vtest[i] = vtest[j];
- vtest[j] = temp;
- }
- }
- }
- // Printing the resulting array
- printf("[ ");
- for (size_t i = 0; i < LEN; i++) {
- printf("%d ", vtest[i]);
- }
- printf("]\n");
- // Asking the element to be searched for
- int to_find;
- printf("Insert to find: ");
- scanf("%d", &to_find);
- // Calling binary search for the result
- printf("Found: %s", binary_search(vtest, LEN, to_find) ? "true" : "false");
- return 0;
- }
- // Loop implementation
- bool binary_search(int v[], size_t length, int to_find) {
- size_t i = 0, j = length;
- while (j - i > 1) {
- // (i + j) / 2
- size_t mid = (i + (j - i) / 2);
- if (v[mid] < to_find)
- i = mid;
- if (v[mid] > to_find)
- j = mid;
- if (v[mid] == to_find)
- return true;
- }
- printf("i: %d, j: %d\n", i, j);
- return v[i] == to_find || v[j] == to_find;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement