Last active
July 8, 2023 06:37
-
-
Save sgeos/a3fa4f5bd1f21b2cdce9367fb05ad281 to your computer and use it in GitHub Desktop.
C qsort example. It takes a list of values from the command line and sorts them in ascending order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
void usage(const char *pProgramName) { | |
printf("Usage: %s x y z ...\n", pProgramName); | |
printf("Example: %s 818 -3 566 5 12 100 12 25\n", pProgramName); | |
printf(" This program will sort numbers in ascending order.\n"); | |
} | |
/*** | |
* Input: argc, argv, an optional array, and the array length | |
* Output: total number of scanned items | |
* | |
* All scanned items are stored in the array if it is supplied. | |
* This function can be run once to get the length of the array, | |
* and a second time to actually populate the array. | |
*/ | |
size_t parse_args(int argc, const char *argv[], int *pArray, size_t pLength) { | |
size_t index = 0; | |
// skip arv[0] | |
for (int i = 1; i < argc; i++) { | |
int value_scanned; | |
int items_scanned = sscanf(argv[i], "%d", &value_scanned); | |
if (NULL != pArray && index < pLength) { | |
pArray[index] = value_scanned; | |
} | |
// EOF is negative | |
if (0 < items_scanned) { | |
index += items_scanned; | |
} | |
} | |
// final index is the total number of scanned items | |
return index; | |
} | |
void print_array(int *pArray, size_t pLength) { | |
int i; | |
for (i = 0 ; i < pLength - 1; i++) { | |
printf("%d ", pArray[i]); | |
} | |
printf("%d\n", pArray[i]); | |
} | |
int qsort_compare(const void *pA, const void *pB) { | |
return (*(int*)pA - *(int*)pB); | |
} | |
int main (int argc, const char *argv[]) { | |
size_t length = parse_args(argc, argv, NULL, 0); | |
int array[length]; | |
parse_args(argc, argv, array, length); | |
if (length < 1) { | |
usage(argv[0]); | |
return 1; | |
} else { | |
qsort(array, length, sizeof(int), qsort_compare); | |
print_array(array, length); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
qsort_ascending: qsort_ascending.c | |
$(CC) -o $@ $^ | |
test: qsort_ascending | |
./qsort_ascending || true # pipe to ignore error | |
./qsort_ascending 818 -3 566 5 12 100 12 25 | |
./qsort_ascending 0 | |
./qsort_ascending 1 -1 0 0 0 0 0 | |
.PHONY: clean | |
clean: | |
rm -f *.o *~ core qsort_ascending |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Although this is a
qsort()
example, theparse_args()
function took the most time to get right.