blob: 98d2db264f9b2a3c88afe4f014bf2c6b15fbd6f8 [file] [log] [blame]
Werner Zehbd660e22019-02-19 13:34:12 +01001/*
2 * This file is part of the coreboot project.
3 *
Werner Zehbd660e22019-02-19 13:34:12 +01004 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 2 of the License.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13
14#include <commonlib/helpers.h>
15#include <commonlib/sort.h>
16
17/* Implement a simple Bubble sort algorithm. Reduce the needed number of
18 iterations by taking care of already sorted entries in the list. */
19void bubblesort(int *v, size_t num_entries, sort_order_t order)
20{
21 size_t i, j;
22 int swapped;
23
Werner Zeh1115f632019-03-12 07:11:11 +010024 /* Make sure there are at least two entries to sort. */
25 if (num_entries < 2)
26 return;
27
Werner Zehbd660e22019-02-19 13:34:12 +010028 for (j = 0; j < num_entries - 1; j++) {
29 swapped = 0;
30 for (i = 0; i < num_entries - j - 1; i++) {
31 switch (order) {
32 case NUM_ASCENDING:
33 if (v[i] > v[i + 1]) {
34 SWAP(v[i], v[i + 1]);
35 swapped = 1;
36 }
37 break;
38 case NUM_DESCENDING:
39 if (v[i] < v[i + 1]) {
40 SWAP(v[i], v[i + 1]);
41 swapped = 1;
42 }
43 break;
44 default:
45 return;
46 }
47 }
48 if (!swapped)
49 break;
50 }
51}