This repository has been archived on 2019-08-09. You can view files and clone it, but cannot push or open issues or pull requests.
s6-pa-tp/TP10/exo3.c
2017-04-03 15:10:31 +02:00

73 lines
1.4 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// 3.1.1
// À mon avis les void* correspondent à n'importe quel type
// 3.1.2
int superieur(const void* A, const void* B) {
int a = *(int*) A;
int b = *(int*) B;
if (a > b) {
return 1;
} else if (a == b) {
return 0;
} else {
return -1;
}
}
int inferieur(const void* A, const void* B) {
int a = *(int*) A;
int b = *(int*) B;
if (a < b) {
return 1;
} else if (a == b) {
return 0;
} else {
return -1;
}
}
#define SIZE 5
#define STR_SIZE 255
void afficherTableau(int t[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("t[%d] = %d\n", i, t[i]);
}
}
int cmpstr(const void* A, const void* B) {
const char* a = (const char*)A;
const char* b = (const char*)B;
return strcmp(a, b);
}
int main() {
int t[SIZE] = {1, 4, 7, 9, 3};
printf("Tri avec inferieur\n");
qsort(t, SIZE, sizeof(int), inferieur);
afficherTableau(t, SIZE);
printf("Tri avec superieur\n");
qsort(t, SIZE, sizeof(int), superieur);
afficherTableau(t, SIZE);
char c[SIZE][STR_SIZE] = {"Bonjour,\0", "comment\0", "allez\0", "vous\0", "?\0"};
/* int (compare(const void*, const void*)) = strcmp; */
printf("Tri avec strcmp\n");
qsort(c, SIZE, sizeof(char) * STR_SIZE, cmpstr);
int i;
for (i = 0; i < SIZE; i++) {
printf("t[%d] = %s\n", i, c[i]);
}
}