Browse code

Add selection sort.

Xavier G authored on 24/08/2016 00:47:23
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 selection sort:
12
+ */
13
+void array_sort(unsigned int **array, unsigned int count) {
14
+	unsigned int *src;           /* Unsorted, source array. */
15
+	unsigned int i, j;           /* Indices. */
16
+	unsigned int smallest_value; /* Smallest value in the unsorted sublist. */
17
+	unsigned int smallest_index; /* Index of the smallest value in the unsorted sublist. */
18
+
19
+	/* Do nothing unless there are at least two items to sort: */
20
+	if (count < 2) return;
21
+
22
+	/* Selection-sort is an in-place algorithm, i.e. we work directly on the
23
+	provided array: */
24
+	src = *array;
25
+
26
+	for (i = 0; i < count - 1; ++ i) {
27
+		/* Find the smallest element in the unsorted sublist: */
28
+		smallest_value = src[i];
29
+		smallest_index = i;
30
+		for (j = i + 1; j < count; ++ j) {
31
+			if (src[j] < smallest_value) {
32
+				smallest_value = src[j];
33
+				smallest_index = j;
34
+			}
35
+		}
36
+
37
+		/* Exchange it with the leftmost unsorted element: */
38
+		if (smallest_index != i) {
39
+			src[smallest_index] = src[i];
40
+			src[i] = smallest_value;
41
+		}
42
+
43
+		/* Move the sublist boundaries one element to the right: */
44
+		/* (this is done by "++ i" in the for loop) */
45
+	}
46
+}
47
+
48
+#define ARRAY_SORT 1
49
+#include "common.c"