TP 11 exo1: affecting a value cost less than branching
[TD_C.git] / TP_13 / exo1 / lib / sort.c
CommitLineData
33b9c646
JB
1#include "utils.h"
2#include "sort.h"
3
4bool ascending(int a, int b) {
5 return a > b;
6}
7
8bool descending(int a, int b) {
9 return a < b;
10}
11
e4001676
JB
12bool ascending_and_even(int a, int b) {
13 return (ascending(a, b) && (a % 2 == 0));
14}
15
16bool ascending_and_odd(int a, int b) {
17 return (ascending(a, b) && (a % 2 != 0));
18}
19
20static bool sort_first(int* array, unsigned length, criteria_cb criteria) {
33b9c646 21 bool rt = false;
e4001676 22 for (unsigned i = 0; i < length-1; i++) {
33b9c646 23 if (criteria(array[i], array[i+1])) {
0139cafd 24 swap_int(&array[i], &array[i+1]);
c944d83b 25 rt = true;
33b9c646
JB
26 }
27 }
28 return rt;
29}
30
31/* this function is awaited in the array.c file */
e4001676 32void sort_bubble_array(int* array, unsigned length, criteria_cb criteria) {
33b9c646
JB
33 bool rt;
34 do {
35 rt = sort_first(array, length, criteria);
36 } while (rt);
37}