summaryrefslogtreecommitdiff
path: root/src/commonlib/sort.c
blob: cdb94d3c7f2d29169839d8840c483cb08d61a59c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* SPDX-License-Identifier: GPL-2.0-only */
/* This file is part of the coreboot project. */

#include <commonlib/helpers.h>
#include <commonlib/sort.h>

/* Implement a simple Bubble sort algorithm. Reduce the needed number of
   iterations by taking care of already sorted entries in the list. */
void bubblesort(int *v, size_t num_entries, sort_order_t order)
{
	size_t i, j;
	int swapped;

	/* Make sure there are at least two entries to sort. */
	if (num_entries < 2)
		return;

	for (j = 0; j < num_entries - 1; j++) {
		swapped = 0;
		for (i = 0; i < num_entries - j - 1; i++) {
			switch (order) {
			case NUM_ASCENDING:
				if (v[i] > v[i + 1]) {
					SWAP(v[i], v[i + 1]);
					swapped = 1;
				}
				break;
			case NUM_DESCENDING:
				if (v[i] < v[i + 1]) {
					SWAP(v[i], v[i + 1]);
					swapped = 1;
				}
				break;
			default:
				return;
			}
		}
		if (!swapped)
			break;
	}
}