Created
November 15, 2017 01:19
-
-
Save dvejmz/1d5597b9f3f310b3f00e6a967c129f2c to your computer and use it in GitHub Desktop.
Simple insertion sort
This file contains 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 <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