102 lines
2.3 KiB
C
102 lines
2.3 KiB
C
#include <assert.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
void printt(int t[], int n) {
|
|
printf("[");
|
|
for (int i = 0; i < n; i++) {
|
|
printf("%d,", t[i]);
|
|
}
|
|
printf("]\n");
|
|
}
|
|
|
|
// Exercice 1
|
|
void insertion_sort(int t[], int n) {
|
|
for (int i = 0; i < n; i++) {
|
|
int x = t[i];
|
|
int j = i - 1;
|
|
while (j >= 0 && t[j] > x) {
|
|
t[j + 1] = t[j];
|
|
j--;
|
|
}
|
|
t[j + 1] = x;
|
|
}
|
|
}
|
|
void selection_sort(int t[], int n) {
|
|
for (int i = 0; i < n; i++) {
|
|
int min = t[i];
|
|
int min_i = i;
|
|
for (int j = i; j < n; j++) {
|
|
if (t[j] < min) {
|
|
min = t[j];
|
|
min_i = j;
|
|
}
|
|
}
|
|
t[min_i] = t[i];
|
|
t[i] = min;
|
|
}
|
|
}
|
|
|
|
// Exercice 2
|
|
void cocktail_sort(int t[], int n) {
|
|
for (int i = 0; i < n / 2; i++) {
|
|
for (int j = i; j < n - i - 1; j++) {
|
|
if (t[j] > t[j + 1]) {
|
|
int tmp = t[j + 1];
|
|
t[j + 1] = t[j];
|
|
t[j] = tmp;
|
|
}
|
|
}
|
|
for (int j = n - i - 2; j >= i; j--) {
|
|
if (t[j] > t[j + 1]) {
|
|
int tmp = t[j + 1];
|
|
t[j + 1] = t[j];
|
|
t[j] = tmp;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Exercice 4
|
|
void counting_sort(int t[], int n, int k) {
|
|
int *counts = malloc(k * sizeof(int));
|
|
for (int i = 0; i < k; i++) {
|
|
counts[i] = 0;
|
|
}
|
|
for (int i = 0; i < n; i++) {
|
|
counts[t[i]] += 1;
|
|
}
|
|
int len = 0;
|
|
for (int i = 0; i < k && len < n; i++) {
|
|
for (int j = 0; j < counts[i]; j++) {
|
|
t[len] = i;
|
|
len++;
|
|
}
|
|
}
|
|
free(counts);
|
|
}
|
|
|
|
const int t[] = {5, 3, 9, 0, 5, 0};
|
|
const int sorted[] = {0, 0, 3, 5, 5, 9};
|
|
const int n = 6;
|
|
|
|
int main() {
|
|
int t1[n];
|
|
memcpy(t1, t, n * sizeof(int));
|
|
insertion_sort(t1, n);
|
|
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
|
|
|
memcpy(t1, t, n * sizeof(int));
|
|
selection_sort(t1, n);
|
|
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
|
|
|
memcpy(t1, t, n * sizeof(int));
|
|
cocktail_sort(t1, n);
|
|
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
|
|
|
memcpy(t1, t, n * sizeof(int));
|
|
counting_sort(t1, n, 10);
|
|
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
|
}
|