Browse code

Make sorting stable

C's stdlib's qsort isn't a stable sort. We want it to be so that any
equivalent matches are stored in the order they came in.

John Hawthorn authored on 07/06/2016 08:58:41
Showing 1 changed files

... ...
@@ -15,12 +15,21 @@ static int cmpchoice(const void *_idx1, const void *_idx2) {
15 15
 	const struct scored_result *a = _idx1;
16 16
 	const struct scored_result *b = _idx2;
17 17
 
18
-	if (a->score == b->score)
19
-		return 0;
20
-	else if (a->score < b->score)
18
+	if (a->score == b->score) {
19
+		/* To ensure a stable sort, we must also sort by the string
20
+		 * pointers. We can do this since we know all the stings are
21
+		 * from a contiguous memory segment (buffer in choices_t).
22
+		 */
23
+		if (a->str < b->str) {
24
+			return -1;
25
+		} else {
26
+			return 1;
27
+		}
28
+	} else if (a->score < b->score) {
21 29
 		return 1;
22
-	else
30
+	} else {
23 31
 		return -1;
32
+	}
24 33
 }
25 34
 
26 35
 static void *safe_realloc(void *buffer, size_t size) {