1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10000
void swap(int *a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
void randomize(int* a) { for (int i = 0; i < SIZE; i++) a[i] = rand(); }
int check(int *a) {
for (int i = 1; i < SIZE; i++) if (a[i] < a[i-1]) return 0;
return 1;
}
void insertion(int *a) {
for (int i = 0; i < SIZE; i++)
for (int j = i; j > 0 && a[j] < a[j-1]; j--)
swap(a, j, j - 1);
}
void selection(int *a) {
for (int i = 0; i < SIZE; i++) {
int k = i;
for (int j = i; j < SIZE; j++)
if (a[j] < a[k])
k = j;
swap(a, i, k);
}
}
void bubble(int *a) {
for (int i = 0; i < SIZE; i+= 1)
for (int j = i - 1; j >= 0 && a[j] > a[j + 1]; j--)
swap(a, j, j + 1);
}
void test(const char *name, void (*f)(int*)) {
int a[SIZE];
randomize(a);
f(a);
printf("%s: %s\n", name, check(a) ? "sorted" : "not sorted");
}
int main() {
srand(time(NULL));
test("Insertion", insertion);
test("Selection", selection);
test("Bubble", bubble);
return 0;
}
|