Skip to content

Instantly share code, notes, and snippets.

@futureperfect
Created February 3, 2014 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save futureperfect/8794121 to your computer and use it in GitHub Desktop.
Save futureperfect/8794121 to your computer and use it in GitHub Desktop.
C command line list sorting w/ sort function extensibility and comparator extensibility
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
void die(const char *message)
{
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
typedef int (*compare_cb)(int a, int b);
typedef int *(*sort_function_cb)(int *numbers, int count, compare_cb cmp);
int increasing(int a, int b) {
return a - b;
}
int decreasing(int a, int b) {
return b - a;
}
int *insertion_sort(int *numbers, int count, compare_cb cmp) {
int i = 0;
int j = 0;
int *result = malloc(count * sizeof(int));
if(!result) die("Memory error");
memcpy(result, numbers, sizeof(int) * count);
for(i = 1; i < count; i++) {
j = i;
while(j > 0 && cmp(result[j-1], result[j]) > 0) {
swap(&result[j-1], &result[j]);
j--;
}
}
return result;
}
int *bubble_sort(int *numbers, int count, compare_cb cmp) {
int i = 0;
int j = 0;
int *result = malloc(count * sizeof(int));
if(!result) die("Memory error.");
memcpy(result, numbers, sizeof(int) * count);
for(i = 0; i < count; i++) {
for(j = 0; j < count - 1; j++) {
if(cmp(result[j], result[j + 1]) > 0) {
swap(&result[j], &result[j + 1]);
}
}
}
return result;
}
void print_array(int *numbers, int count) {
int i = 0;
for(i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
void test_sort(sort_function_cb sort_fn, int *numbers, int count, compare_cb cmp) {
int *result = sort_fn(numbers, count, cmp);
print_array(result, count);
/* more good C citizenship */
free(result);
}
int main(int argc, char* argv[])
{
int i = 0;
int count = argc - 1;
int *numbers;
if(argc < 2) die("Usage ./sort 5 1 4 2 3 6\n");
/* allocate space for int array */
numbers = malloc(count * sizeof(int));
if (!numbers) die("Memory error.");
/* take in command line arguments */
/* convert into integer array */
for(i = 0; i < count; i++) {
numbers[i] = atoi(argv[i + 1]);
}
printf("Bubble sort:\n");
/* sort them */
test_sort(bubble_sort, numbers, count, increasing);
test_sort(bubble_sort, numbers, count, decreasing);
printf("Insertion sort:\n");
test_sort(insertion_sort, numbers, count, increasing);
test_sort(insertion_sort, numbers, count, decreasing);
/* Be a good Citizen and free your mallocs. For America. */
free(numbers);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment