aboutsummaryrefslogtreecommitdiff
path: root/src/sort_example.c
diff options
context:
space:
mode:
authorThorsten Töpper <atsutane@freethoughts.de>2025-09-11 21:58:03 +0200
committerThorsten Töpper <atsutane@freethoughts.de>2025-09-11 21:58:03 +0200
commitae3b1829f9731662b5e2b626655a619733101209 (patch)
tree32af93ec8facd3e7d96764b1ececffabd7d0dc9a /src/sort_example.c
parent3d4e2fc261d3471eac5e68c5905ab5980f0ff89f (diff)
downloadsmall-utils-ae3b1829f9731662b5e2b626655a619733101209.tar.gz
small-utils-ae3b1829f9731662b5e2b626655a619733101209.tar.bz2
Example code for libc qsort and bsearch
Diffstat (limited to 'src/sort_example.c')
-rw-r--r--src/sort_example.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/sort_example.c b/src/sort_example.c
new file mode 100644
index 0000000..7506cde
--- /dev/null
+++ b/src/sort_example.c
@@ -0,0 +1,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;
+}