-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.c
66 lines (56 loc) · 1023 Bytes
/
quick_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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void quick_sort(int* array, int begin, int end) {
int i, j, pivo, aux;
i = begin;
j = end;
pivo = array[(begin+end) / 2];
while (i < j) {
while (array[i] < pivo) {
i++;
}
while (array[j] > pivo) {
j--;
}
if (i <= j) {
aux = array[i];
array[i] = array[j];
array[j] = aux;
i++;
j--;
}
if (j > begin) {
quick_sort(array, begin, j);
}
if (i < end) {
quick_sort(array, i, end);
}
}
}
void print_array(int* array, int len) {
int i;
printf("[");
for (i = 0; i < len; i++) {
if (i == len-1) {
printf("%d", array[i]);
} else {
printf("%d, ", array[i]);
}
}
printf("]\n");
}
int main(int argc, const char *argv[])
{
int len;
int array[] = { 4, 5, 3, 2, 1 };
int *sorted;
len = sizeof(array) / sizeof(int);
sorted = malloc(sizeof(array));
memcpy(sorted, array, sizeof(array));
quick_sort(sorted, 0, len-1);
print_array(array, len);
print_array(sorted, len);
free(sorted);
return 0;
}