example4_sorting_searching.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cstdlib>
#include <iostream>
#include <algorithm>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Sorting
    std::qsort(arr, n, sizeof(int), compare);

    std::cout << "Sorted array: ";
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Searching
    int key = 25;
    int* item = (int*)std::bsearch(&key, arr, n, sizeof(int), compare);

    if (item != NULL) {
        std::cout << key << " found at position " << (item - arr) << std::endl;
    } else {
        std::cout << key << " not found in the array" << std::endl;
    }

    return EXIT_SUCCESS;
}
Back to cstdlib