summaryrefslogtreecommitdiff
path: root/src/choices.c
diff options
context:
space:
mode:
authorJohn Hawthorn <john.hawthorn@gmail.com>2016-06-07 01:58:41 -0700
committerJohn Hawthorn <john.hawthorn@gmail.com>2016-06-08 17:39:52 -0700
commit3b23f5714e5d4625117c52988edd972d3587db23 (patch)
treeda47a606c12386b8c40165b2951c34f449a5005b /src/choices.c
parente176ba933813f9fc4c85a25aef8b53e7dd50859d (diff)
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.
Diffstat (limited to 'src/choices.c')
-rw-r--r--src/choices.c17
1 files changed, 13 insertions, 4 deletions
diff --git a/src/choices.c b/src/choices.c
index ba25749..d9445c5 100644
--- a/src/choices.c
+++ b/src/choices.c
@@ -15,12 +15,21 @@ static int cmpchoice(const void *_idx1, const void *_idx2) {
const struct scored_result *a = _idx1;
const struct scored_result *b = _idx2;
- if (a->score == b->score)
- return 0;
- else if (a->score < b->score)
+ if (a->score == b->score) {
+ /* To ensure a stable sort, we must also sort by the string
+ * pointers. We can do this since we know all the stings are
+ * from a contiguous memory segment (buffer in choices_t).
+ */
+ if (a->str < b->str) {
+ return -1;
+ } else {
+ return 1;
+ }
+ } else if (a->score < b->score) {
return 1;
- else
+ } else {
return -1;
+ }
}
static void *safe_realloc(void *buffer, size_t size) {