-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort.c
70 lines (54 loc) · 1.18 KB
/
sort.c
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include "sort.h"
__attribute__ ((weak))
int compare(int a, int b) {
return a - b;
}
void bubble_sort(int *numbers, unsigned count) {
int temp;
int i, j;
for(i = 0; i < count; i++) {
for(j = 0; j < count - 1; j++) {
if(compare(numbers[j+1], numbers[j]) < 0) {
temp = numbers[j+1];
numbers[j+1] = numbers[j];
numbers[j] = temp;
}
}
}
}
void insertion_sort(int *numbers, unsigned count) {
int new[count];
unsigned new_count = 0;
while (new_count < count) {
int num = numbers[new_count];
unsigned idx = 0;
while (true) {
if (idx == new_count) {
new[idx] = num;
break;
}
if (compare(num, new[idx]) < 0) {
unsigned i;
for (i=new_count;i>idx;i--) {
new[i] = new[i-1];
}
new[i] = num;
break;
}
idx++;
}
new_count++;
}
memcpy(numbers, new, count*sizeof(int));
}
int q_compare(const void *a, const void *b) {
compare(*(int*)a, *(int*)b);
}
void q_sort_wrapper(int *numbers, unsigned count){
qsort(numbers, count, sizeof(int), q_compare);
}
sorting_fn sorting_fns[] = {bubble_sort, insertion_sort, q_sort_wrapper, NULL};