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);
- bool binary_search_rec(int v[], size_t length, int to_find, size_t i, size_t j);
- bool binary_search_rec_2(int v[], size_t length, int to_find, size_t i,
- size_t j) int sum(int v[], size_t length);
- int sum_rec(int v[], size_t length, size_t index);
- 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\n", binary_search(vtest, LEN, to_find) ? "true" : "false");
- printf("Found rec: %s\n",
- binary_search_rec(vtest, LEN, to_find, 0, LEN) ? "true" : "false");
- printf("Sum: %d\n", sum(vtest, LEN));
- printf("Sum rec: %d", sum_rec(vtest, LEN, 0));
- return 0;
- }
- int sum(int v[], size_t length) {
- int s = 0;
- for (size_t i = 0; i < length; i++) {
- s += v[i];
- }
- return s;
- }
- int sum_rec(int v[], size_t length, size_t index) {
- if (length == index)
- return 0;
- return v[index] + sum_rec(v, length, index + 1);
- }
- // 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;
- }
- bool binary_search_rec(int v[], size_t length, int to_find, size_t i,
- size_t j) {
- if (!(j - i > 1))
- return v[i] == to_find || v[j] == to_find;
- // (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;
- return binary_search_rec(v, length, to_find, i, j);
- }
- bool binary_search_rec_2(int v[], size_t length, int to_find, size_t i,
- size_t j) {
- if (!(j - i > 1))
- return v[i] == to_find || v[j] == to_find;
- // (i + j) / 2
- size_t mid = (i + (j - i) / 2);
- if (v[mid] < to_find)
- return binary_search_rec(v, length, to_find, mid, j);
- if (v[mid] > to_find)
- return binary_search_rec(v, length, to_find, i, mid);
- if (v[mid] == to_find)
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement