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
|
/*
* vim:ts=4:sw=4:expandtab
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
int sort_comp(const void *a, const void *b) {
/* casting is dark magic */
char * const *A = a;
char * const *B = b;
return strcmp(*A,*B);
}
bool search_in_array(char *str, char *array[], size_t items) {
char *cptr = NULL;
printf (" ==> Search for '%s'\n", str);
cptr = bsearch(&str, array, items, sizeof(char*), sort_comp);
return (cptr==NULL) ? false : true ;
}
int main(void) {
char *array[] = {
"some", "example", "test", "data", "for", "sort",
"and", "search", "duplicate", "data" };
size_t items = sizeof(array)/sizeof(char*) ;
size_t i = 0;
printf(" ==> raw test data\n");
for (i=0; i<items; i++) {
printf("\t%2lu - %s\n", i, array[i]);
}
printf(" ==> qsort call\n");
qsort(array, items, sizeof(char*), sort_comp);
printf(" ==> sorted test data\n");
for (i=0; i<items; i++) {
printf("\t%2lu - %s\n", i, array[i]);
}
if (search_in_array("data", array, items)) {
printf("\t-> positive hit\n");
} else {
printf("\t-> not found\n");
}
if (search_in_array("non-existing", array, items)) {
printf("\t-> positive hit\n");
} else {
printf("\t-> not found\n");
}
return EXIT_SUCCESS;
}
|