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.
| ... | ... |
@@ -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) {
|