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
|
// Bubble sort and insertion sort of the same eight numbers, argv[1] times
// (by default once). Exits with the smallest plus the largest.
#include <stdlib.h>
#include <string.h>
#define N 8
// Not const, not static: -O2 must sort at run time, not when compiling.
int unsorted[N] = {5, 2, 9, 1, 7, 3, 8, 4};
static void bubble(int *a, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
static void insertion(int *a, int n) {
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
int main(int argc, char **argv) {
int rounds = argc > 1 ? atoi(argv[1]) : 1;
int bubbled[N], inserted[N];
while (rounds-- > 0) {
memcpy(bubbled, unsorted, sizeof unsorted);
memcpy(inserted, unsorted, sizeof unsorted);
bubble(bubbled, N);
insertion(inserted, N);
}
return bubbled[0] + inserted[N - 1];
}
|