Browse code

Insertion sort: get closer to the academical implementation.

Xavier G authored on 23/08/2016 22:58:25
Showing 1 changed files
... ...
@@ -12,7 +12,8 @@
12 12
  */
13 13
 void array_sort(unsigned int **array, unsigned int count) {
14 14
 	unsigned int *src;             /* Unsorted, source array. */
15
-	unsigned int i, insert_idx, k; /* Indices. */
15
+	unsigned int i;                /* Index to iterate over the array. */
16
+	int j;                         /* Index for shifts and insertions. */
16 17
 	unsigned int register value;   /* Value being repositioned. */
17 18
 	unsigned int insertions;       /* Stats: # of insertions. */
18 19
 	unsigned int moved_items;      /* Stats: # of moved items. */
... ...
@@ -28,18 +29,16 @@ void array_sort(unsigned int **array, unsigned int count) {
28 29
 	moved_items = 0;
29 30
 	for (i = 1; i < count; ++ i) {
30 31
 		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;
32
+		/* Look back for the position where src[i] ought to be inserted,
33
+		shifting items on the way: */
34
+		for (j = i - 1; j >= 0 && src[j] > value; -- j) {
35
+			src[j + 1] = src[j];
36
+			++ moved_items;
37
+		}
38
+		/* If needed, insert src[i] to its new, correct position: */
39
+		if (j + 1 != i) {
40
+			src[j + 1] = value;
41 41
 			++ insertions;
42
-			moved_items += i - insert_idx;
43 42
 		}
44 43
 	}
45 44
 	printf("Insertion sort: made %u insertions, moved %u items.\n", insertions, moved_items);