Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple insertion sort
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int issort(
void *data,
int size,
int esize,
int (*compare)(const void *key1, const void *key2)
) {
char *a = data;
void *key;
int i, j;
// Allocate storage for the key element.
if ((key = (char *)malloc(esize)) == NULL) {
return -1;
}
// Repeatedly insert a key element among the sorted elements.
for (j = 1; j < size; ++j) {
memcpy(key, &a[j * esize], esize);
i = j - 1;
// Determine the position at which to insert the key element.
while (i >= 0 && compare(&a[i * esize], key) > 0) {
memcpy(&a[(i + 1) * esize], &a[i * esize], esize);
--i;
}
memcpy(&a[(i + 1) * esize], key, esize);
}
// Free the storage allocated for sorting.
free(key);
return 0;
}
int compare_number(const void *key1, const void *key2) {
const int n1 = (const int)key1;
const int n2 = (const int)key2;
if (n1 > n2) {
return -1;
} else if (n2 > n1) {
return 1;
}
return 0;
}
void print_int_array(const int *arr, int size) {
if (arr == NULL || size < 1) {
return;
}
printf("SORTED DATA ARRAY\n"
"=================\n\n");
printf("[ ");
for (int i = 0; i < size; ++i) {
printf("%d%s", arr[i], (((i + 1) != size) ? ", " : ""));
}
printf(" ]\n");
}
int main(int argc, char *argv[]) {
int original_data[] = { 0, 3, 5, 6, 8, 5, 4, 2 };
int data[8];
memcpy(data, original_data, 8);
const int size = 8;
const int esize = 8;
int rc = issort(data, size, esize, compare_number);
printf("Sort was a %s.\n\n", rc == 0 ? "SUCCESS" : "FAILURE");
print_int_array(original_data, esize);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.