-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-cocktail_sort_list.c
executable file
·74 lines (71 loc) · 1.21 KB
/
101-cocktail_sort_list.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
70
71
72
73
74
#include "sort.h"
/**
* swap - swaps both
* @p: first node to swap
* @c: second node to swap
* @list: list to set null or not
*/
void swap(listint_t *p, listint_t *c, listint_t **list)
{
if (!(p->prev))
{
p->next = c->next;
if (c->next)
c->next->prev = p;
c->next = p;
c->prev = NULL;
p->prev = c;
*list = c;
}
else
{
c->prev->next = c->next;
if (c->next)
c->next->prev = c->prev;
p->prev->next = c;
c->prev = p->prev;
p->prev = c;
c->next = p;
}
}
/**
* cocktail_sort_list - inserts right unsorted side into left sorted side
* @list: doubly linked list to sort
*/
void cocktail_sort_list(listint_t **list)
{
listint_t *c, *nextnode;
int swapped;
if (list == NULL || !(*list) || (*list)->next == NULL)
return;
c = (*list);
do {
swapped = 0;
while (c->next)
{
nextnode = c->next;
if (nextnode && c->n > nextnode->n)
{
swap(c, nextnode, list);
swapped = 1;
print_list((*list));
}
else
c = c->next;
}
c = c->prev;
while (c->prev)
{
nextnode = c->prev;
if (nextnode && c->n < nextnode->n)
{
swap(nextnode, c, list);
swapped = 1;
print_list((*list));
}
else
c = c->prev;
}
c = c->next;
} while (swapped);
}