commit 6368d91574693964af096d7638fe324811816fbb
Author: zerous Naveen Narayanan <zerous@nocebo.space>
Date: Wed, 20 Feb 2019 21:14:47 +0100
Add insertion-sort
Diffstat:
1 file changed, 48 insertions(+), 0 deletions(-)
diff --git a/insertion-sort.c b/insertion-sort.c
@@ -0,0 +1,48 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+/* an implementation of insertion sort */
+
+void isort(int *, size_t, int);
+
+int
+main(int argc, char** argv)
+{
+ int *a;
+ size_t nelem;
+
+ nelem = argc - 1;
+ a = (int *)malloc(1024);
+
+ for(int i = 0; i < nelem; i++) {
+ ++argv;
+ *(a+i) = atoi(*argv);
+ }
+
+ for (size_t i = 1; i < nelem; i++) {
+ isort(a, i, a[i]);
+ }
+
+ for (size_t i = 0; i<nelem; i++)
+ printf("%d ", a[i]);
+ printf("\n");
+
+ free(a);
+
+ return 0;
+}
+
+void
+isort(int a[], size_t i, int val)
+{
+ int j = i - 1;
+
+ while (j >= 0 && a[j] > val) {
+ a[j+1] = a[j];
+ j--;
+ }
+ a[j+1] = val;
+
+ return;
+}
+