Whitespaces cleqnup.
[TD_C.git] / TP_12 / exo1 / exo1.c
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 typedef bool(*compare_cb)(int a, int b);
5
6 bool ascending(int a, int b) {
7 return a > b;
8 }
9
10 bool descending(int a, int b) {
11 return a < b;
12 }
13
14 void swap(int* v1, int* v2) {
15 int tmp = *v1;
16 *v1 = *v2;
17 *v2 = tmp;
18 }
19
20 void displayArray(int* array, int count) {
21 for (int i = 0; i < count; i++) {
22 printf("Value in array at index[%d]= %d\n", i, array[i]);
23 }
24 }
25
26 bool sortFirst(int* array, int length, compare_cb compare) {
27 bool rt = false;
28 for (int i = 0; i < length-1; i++) {
29 if (compare(array[i], array[i+1])) {
30 swap(&array[i], &array[i+1]);
31 if (!rt) { rt = true; };
32 }
33 }
34 return rt;
35 }
36
37 void sortArray(int* array, int length, compare_cb compare) {
38 bool rt;
39 do {
40 rt = sortFirst(array, length, compare);
41 } while (rt);
42 }
43
44 int main() {
45 const int tab_size = 10;
46 int tab[10] = {4, 6, 2, 9, 5, 7, 1, 3, 8, 0};
47
48 printf("\nView array content unsorted:\n");
49 displayArray(tab, tab_size);
50 printf("\nNow, sorting the array ascending...\n");
51 sortArray(tab, tab_size, ascending);
52 printf("\nView array content sorted:\n");
53 displayArray(tab, tab_size);
54 printf("\nNow, sorting the array descending...\n");
55 sortArray(tab, tab_size, descending);
56 printf("\nView array content sorted:\n");
57 displayArray(tab, tab_size);
58
59 return 0;
60 }