td5 exo4
This commit is contained in:
parent
47516dbf42
commit
c0aaecda45
28
td5/td5.c
28
td5/td5.c
@ -1,5 +1,6 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void printt(int t[], int n) {
|
||||
@ -11,7 +12,6 @@ void printt(int t[], int n) {
|
||||
}
|
||||
|
||||
// Exercice 1
|
||||
|
||||
void insertion_sort(int t[], int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
int x = t[i];
|
||||
@ -23,7 +23,6 @@ void insertion_sort(int t[], int n) {
|
||||
t[j + 1] = x;
|
||||
}
|
||||
}
|
||||
|
||||
void selection_sort(int t[], int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
int min = t[i];
|
||||
@ -39,6 +38,7 @@ void selection_sort(int t[], int n) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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++) {
|
||||
@ -58,6 +58,25 @@ void cocktail_sort(int t[], int n) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
@ -74,6 +93,9 @@ int main() {
|
||||
|
||||
memcpy(t1, t, n * sizeof(int));
|
||||
cocktail_sort(t1, n);
|
||||
printt(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);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user