blob: c81356dbd6649a6d67c59d95b321c236b76fd827 (
plain) (
blame)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
/*
* Copyright (C) Igor Sysoev
* Copyright (C) NGINX, Inc.
*/
#include <nxt_main.h>
/*
* Find the middle queue element if the queue has odd number of elements,
* or the first element of the queue's second part otherwise.
*/
nxt_queue_link_t *
nxt_queue_middle(nxt_queue_t *queue)
{
nxt_queue_link_t *middle, *next;
middle = nxt_queue_first(queue);
if (middle == nxt_queue_last(queue)) {
return middle;
}
next = middle;
for ( ;; ) {
middle = nxt_queue_next(middle);
next = nxt_queue_next(next);
if (next == nxt_queue_last(queue)) {
return middle;
}
next = nxt_queue_next(next);
if (next == nxt_queue_last(queue)) {
return middle;
}
}
}
/*
* nxt_queue_sort() provides a stable sort because it uses the insertion
* sort algorithm. Its worst and average computational complexity is O^2.
*/
void
nxt_queue_sort(nxt_queue_t *queue,
nxt_int_t (*cmp)(const void *data, const nxt_queue_link_t *,
const nxt_queue_link_t *), const void *data)
{
nxt_queue_link_t *link, *prev, *next;
link = nxt_queue_first(queue);
if (link == nxt_queue_last(queue)) {
return;
}
for (link = nxt_queue_next(link);
link != nxt_queue_tail(queue);
link = next)
{
prev = nxt_queue_prev(link);
next = nxt_queue_next(link);
nxt_queue_remove(link);
do {
if (cmp(data, prev, link) <= 0) {
break;
}
prev = nxt_queue_prev(prev);
} while (prev != nxt_queue_head(queue));
nxt_queue_insert_after(prev, link);
}
}
|