80 lines
1.7 KiB
C
80 lines
1.7 KiB
C
#include <assert.h>
|
|
#include <stdio.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;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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[6];
|
|
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);
|
|
printt(t1, n);
|
|
assert(memcmp(t1, sorted, n * sizeof(int)) == 0);
|
|
}
|