-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
86 lines (65 loc) · 1.82 KB
/
main.c
File metadata and controls
86 lines (65 loc) · 1.82 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
struct Pair
{
const char* const key;
const char* const value;
};
static struct Pair thingsMap[] = {
{"mercedes-benz", "car"},
{"polar bear", "animal"},
{"eiffel tower", "building"},
{"banana", "fruit"},
{"bmw", "car"},
{"dog", "animal"},
{"louvre", "building"},
{"carrot", "vegetable"},
{"audi", "car"},
{"cat", "animal"},
{"taj mahal", "building"},
{"orange", "fruit"}
};
const int MAP_ELEMENT_SIZE = sizeof(thingsMap[0]);
const int MAP_ELEMENTS_COUNT = sizeof(thingsMap) / sizeof(thingsMap[0]);
const char* const KEY_TO_FIND = "louvre";
static int compareMapElements(const void* const lhs, const void* const rhs)
{
const struct Pair* const a = lhs;
const struct Pair* const b = rhs;
if (*a->key < *b->key) return -1;
if (*a->key > *b->key) return 1;
return 0;
}
static void printMapElements()
{
int idx = 0;
for (; idx < MAP_ELEMENTS_COUNT; ++idx)
{
printf("Key: %s, Value: %s\n",
thingsMap[idx].key,
thingsMap[idx].value);
}
}
int main()
{
printf("Unsorted map\n");
printMapElements();
qsort(thingsMap,
MAP_ELEMENTS_COUNT,
MAP_ELEMENT_SIZE,
compareMapElements);
printf("\nSorted map\n");
printMapElements();
const struct Pair mapKey = {.key = KEY_TO_FIND};
printf("\nSearching %s in the map...\n", mapKey.key);
const struct Pair* const mapElement = bsearch(&mapKey,
thingsMap,
MAP_ELEMENTS_COUNT,
MAP_ELEMENT_SIZE,
compareMapElements);
if (mapElement)
{
printf("%s found!\n", mapElement->key);
}
return 0;
}