prog_avancee_C/TP4/ex_4.c

75 lines
1.4 KiB
C
Raw Permalink Normal View History

2024-10-22 13:03:17 +02:00
#include <stdio.h>
int less(int a, int b);
int more(int a, int b);
int pair_more(int a, int b);
void sort(int * tab, int size_tab, int (* sort_func)(int, int));
void print_tab(int * tab, int size) {
printf("tab[%d] = [", size);
for (int i=0; i<size; i++) {
printf("%d ", tab[i]);
}
printf("]\n");
}
int main(int argc, char *argv[]) {
printf("%d, ", less(5, 6));
printf("%d, ", more(5, 6));
printf("%d\n", pair_more(4, 5));
int tab[10] = {6, 9, 0, 5, 3, 7, 4, 8, 1, 2};
print_tab(tab, 10);
sort(tab, 10, less);
print_tab(tab, 10);
sort(tab, 10, more);
print_tab(tab, 10);
sort(tab, 10, pair_more);
print_tab(tab, 10);
return 0;
}
int less(int a, int b) {
if (a < b) {
return 1;
} else {
return -1;
}
}
int more(int a, int b) {
if (a > b) {
return 1;
} else {
return -1;
}
}
int pair_more(int a, int b) {
if (a%2==0) {
if (b%2!=0) {
return 1;
} else {
return more(a, b);
}
}
return -1;
}
void sort(int * tab, int size_tab, int (* sort_func)(int, int)) {
int i,j, tmp;
for (i=0; i<size_tab-1; i++) {
for (j=i+1; j<size_tab; j++) {
if (sort_func(tab[i], tab[j]) == -1) {
tmp = tab[j];
tab[j] = tab[i];
tab[i] = tmp;
}
}
}
}