C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
algorithms/searching/main.c
Go to the documentation of this file.
1/**
2 * @file main.c
3 * @brief Binary search CLI demo.
4 *
5 * Usage:
6 * bsearch <target> <num1> <num2> ...
7 *
8 * The trailing numbers are sorted internally (insertion sort, since the
9 * input list is small) before the search runs.
10 */
11
12#include "../sorting/sorts.h"
13#include "binary_search.h"
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17
18static void print_array(const int *arr, size_t n) {
19 printf("[");
20 for (size_t i = 0; i < n; i++) {
21 printf("%d", arr[i]);
22 if (i + 1 < n) printf(", ");
23 }
24 printf("]");
25}
26
27int main(int argc, char *argv[]) {
28 if (argc < 3) {
29 printf("Usage: %s <target> <num1> <num2> ...\n", argv[0]);
30 printf("\nExample: %s 7 3 1 9 7 4 2\n", argv[0]);
31 return EXIT_FAILURE;
32 }
33
34 int target = atoi(argv[1]);
35 size_t n = (size_t)(argc - 2);
36 int *arr = malloc(n * sizeof(int));
37 if (!arr) return EXIT_FAILURE;
38
39 for (size_t i = 0; i < n; i++) arr[i] = atoi(argv[i + 2]);
40
41 insertion_sort_ints(arr, n);
42
43 printf("Sorted: ");
44 print_array(arr, n);
45 printf("\nTarget: %d\n", target);
46
47 size_t idx = binary_search_ints(arr, n, target);
48 if (idx == BSEARCH_NOT_FOUND) {
49 printf("Result: not found\n");
50 } else {
51 printf("Result: found at index %zu\n", idx);
52 }
53
54 free(arr);
55 return EXIT_SUCCESS;
56}
static void print_array(const int *arr, size_t n)
int main(void)
Definition benchmark.c:50
size_t binary_search_ints(const int *arr, size_t n, int target)
Binary search on sorted arrays. O(log n) time, O(1) space.
#define BSEARCH_NOT_FOUND
void insertion_sort_ints(int *arr, size_t n)