-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_sort.c
68 lines (56 loc) · 1.39 KB
/
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
67
68
#include <stdio.h>
#include <stdlib.h>
void quick_sort(const char *a[], size_t len);
void print_array(const char * a[], const int size);
int main(void)
{
const char * data[] = {"Joe", "Jenny", "Jill", "John",
"Jeff", "Joyce", "Jerry", "Janice",
"Jake", "Jonna", "Jack", "Jocelyn",
"Jessie", "Jess", "Janet", "Jane"};
int size = 16;
printf("Initial array:\n");
print_array(data, size);
quick_sort(data, size);
printf("Sorted array:\n");
print_array(data, size);
exit(0);
}
int str_lt (const char *x, const char *y) {
for (; *x!='\0' && *y!='\0'; x++, y++) {
if ( *x < *y ) return 1;
if ( *y < *x ) return 0;
}
if ( *y == '\0' ) return 0;
else return 1;
}
void swap_str_ptrs(const char **s1, const char **s2)
{
const char *tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
void quick_sort(const char *a[], size_t len) {
if (len <= 1) {
return;
}
// Partition the array around a pivot.
int pivot = 0;
for (int i = 0; i < len - 1; i++) {
if (str_lt(a[i], a[len - 1])) {
swap_str_ptrs(&a[i], &a[pivot]);
pivot++;
}
}
swap_str_ptrs(&a[pivot], &a[len - 1]);
quick_sort(a, pivot);
quick_sort(a + pivot + 1, len - pivot - 1);
}
void print_array(const char * a[], const int size)
{
printf("[");
for (int i = 0; i < size; i++) {
printf(" %s", a[i]);
}
printf(" ]\n");
}