-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_qsort.c
56 lines (45 loc) · 986 Bytes
/
list_qsort.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
#include "list.h"
#include <stdlib.h>
#ifdef DEBUG
#include <stdio.h>
#endif
list_t* partition(list_t** istart, list_t* end) {
list_t* pivot = *istart;
list_t* np = pivot->next;
list_t** iend;
#ifdef DEBUG
printf("\t[partition start]\t");
list_print(*istart, end);
#endif
pivot->next = end;
iend = &pivot->next;
while (np != end) {
list_t* nnp = np->next;
if (np->data < pivot->data) {
np->next = *istart;
*istart = np;
}
else {
np->next = *iend;
*iend = np;
iend = &np->next;
}
np = nnp;
}
#ifdef DEBUG
printf("\t[partition end]\t");
list_print(*istart, end);
#endif
return pivot;
}
void list_qsort_impl(list_t** istart, list_t* end) {
if (*istart == end || (*istart)->next == end)
return;
list_t* pivot = partition(istart, end);
list_qsort_impl(istart, pivot);
list_qsort_impl(&pivot->next, end);
return;
}
void list_qsort(list_t** ihead) {
list_qsort_impl(ihead, NULL);
}