Angel Pons | ebda03e | 2020-04-02 23:48:05 +0200 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
| 2 | /* This file is part of the coreboot project. */ |
Werner Zeh | bd660e2 | 2019-02-19 13:34:12 +0100 | [diff] [blame] | 3 | |
| 4 | #include <commonlib/helpers.h> |
| 5 | #include <commonlib/sort.h> |
| 6 | |
| 7 | /* Implement a simple Bubble sort algorithm. Reduce the needed number of |
| 8 | iterations by taking care of already sorted entries in the list. */ |
| 9 | void bubblesort(int *v, size_t num_entries, sort_order_t order) |
| 10 | { |
| 11 | size_t i, j; |
| 12 | int swapped; |
| 13 | |
Werner Zeh | 1115f63 | 2019-03-12 07:11:11 +0100 | [diff] [blame] | 14 | /* Make sure there are at least two entries to sort. */ |
| 15 | if (num_entries < 2) |
| 16 | return; |
| 17 | |
Werner Zeh | bd660e2 | 2019-02-19 13:34:12 +0100 | [diff] [blame] | 18 | for (j = 0; j < num_entries - 1; j++) { |
| 19 | swapped = 0; |
| 20 | for (i = 0; i < num_entries - j - 1; i++) { |
| 21 | switch (order) { |
| 22 | case NUM_ASCENDING: |
| 23 | if (v[i] > v[i + 1]) { |
| 24 | SWAP(v[i], v[i + 1]); |
| 25 | swapped = 1; |
| 26 | } |
| 27 | break; |
| 28 | case NUM_DESCENDING: |
| 29 | if (v[i] < v[i + 1]) { |
| 30 | SWAP(v[i], v[i + 1]); |
| 31 | swapped = 1; |
| 32 | } |
| 33 | break; |
| 34 | default: |
| 35 | return; |
| 36 | } |
| 37 | } |
| 38 | if (!swapped) |
| 39 | break; |
| 40 | } |
| 41 | } |