Browse code

Add insertion sort.

Xavier G authored on 23/08/2016 21:54:29
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,49 @@
1
+/**
2
+ * Copyright © 2016 Xavier G. <xavier@kindwolf.org>
3
+ * This work is free. You can redistribute it and/or modify it under the
4
+ * terms of the Do What The Fuck You Want To Public License, Version 2,
5
+ * as published by Sam Hocevar. See the COPYING file for more details.
6
+ */
7
+
8
+#include <stdio.h>
9
+
10
+/*
11
+ * Implementation of insertion sort:
12
+ */
13
+void array_sort(unsigned int **array, unsigned int count) {
14
+	unsigned int *src;             /* Unsorted, source array. */
15
+	unsigned int i, insert_idx, k; /* Indices. */
16
+	unsigned int register value;   /* Value being repositioned. */
17
+	unsigned int insertions;       /* Stats: # of insertions. */
18
+	unsigned int moved_items;      /* Stats: # of moved items. */
19
+
20
+	/* Do nothing unless there are at least two items to sort: */
21
+	if (count < 2) return;
22
+
23
+	/* Insertion-sort is an in-place algorithm, i.e. we work directly on the
24
+	provided array: */
25
+	src = *array;
26
+
27
+	insertions = 0;
28
+	moved_items = 0;
29
+	for (i = 1; i < count; ++ i) {
30
+		value = src[i];
31
+		/* Determine where src[i] should be inserted: */
32
+		for (insert_idx = 0; insert_idx < i && value >= src[insert_idx] ; ++ insert_idx);
33
+		/* printf("%u should be inserted at index %u\n", value, insert_idx); */
34
+		if (insert_idx != i) {
35
+			/* If necessary, shift items in the insert_idx..i range: */
36
+			for (k = i; k > insert_idx; --k) {
37
+				src[k] = src[k - 1];
38
+			}
39
+			/* Insert src[i] at the adequate index: */
40
+			src[insert_idx] = value;
41
+			++ insertions;
42
+			moved_items += i - insert_idx;
43
+		}
44
+	}
45
+	printf("Insertion sort: made %u insertions, moved %u items.\n", insertions, moved_items);
46
+}
47
+
48
+#define ARRAY_SORT 1
49
+#include "common.c"