-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-cocktail_sort_list.c
executable file
·98 lines (88 loc) · 2.38 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "sort.h"
void cocktail_sort_list(listint_t **list);
void swap_node_ahead(listint_t **list, listint_t **tail, listint_t **shaker);
void swap_node_behind(listint_t **list, listint_t **tail, listint_t **shaker);
/**
* cocktail_sort_list - Sorts a doubly LL of integers in ascending order.
*
* @list: Pointer to the list to be sorted.
*/
void cocktail_sort_list(listint_t **list)
{
listint_t *tail, *shaker;
bool shaken = false;
if (list == NULL || *list == NULL || (*list)->next == NULL)
return;
for (tail = *list; tail->next != NULL;)
tail = tail->next;
while (shaken == false)
{
shaken = true;
for (shaker = *list; shaker != tail; shaker = shaker->next)
{
if (shaker->n > shaker->next->n)
{
swap_node_ahead(list, &tail, &shaker);
print_list((const listint_t *)*list);
shaken = false;
}
}
for (shaker = shaker->prev; shaker != *list; shaker = shaker->prev)
{
if (shaker->n < shaker->prev->n)
{
swap_node_behind(list, &tail, &shaker);
print_list((const listint_t *)*list);
shaken = false;
}
}
}
}
/**
* swap_node_ahead - Swap a node in a listint_t doubly-LL.
*
* @list: A pointer to the head of a doubly-linked list of integers.
* @tail: A pointer to the tail of the doubly-linked list.
* @shaker: A pointer to the current swapping node of the cocktail shaker algo.
*/
void swap_node_ahead(listint_t **list, listint_t **tail, listint_t **shaker)
{
listint_t *tmp = (*shaker)->next;
if ((*shaker)->prev != NULL)
(*shaker)->prev->next = tmp;
else
*list = tmp;
tmp->prev = (*shaker)->prev;
(*shaker)->next = tmp->next;
if (tmp->next != NULL)
tmp->next->prev = *shaker;
else
*tail = *shaker;
(*shaker)->prev = tmp;
tmp->next = *shaker;
*shaker = tmp;
}
/**
* swap_node_behind - Swap a node in a listint_t doubly-LL.
*
* @list: A pointer to the head of a doubly-linked list of integers.
* @tail: A pointer to the tail of the doubly-linked list.
* @shaker: A pointer to the current swapping node of the cocktail shaker algo.
*/
void swap_node_behind(listint_t **list, listint_t **tail, listint_t **shaker)
{
listint_t *tmp = (*shaker)->prev;
if ((*shaker)->next != NULL)
(*shaker)->next->prev = tmp;
else
*tail = tmp;
tmp->next = (*shaker)->next;
(*shaker)->prev = tmp->prev;
if (tmp->prev != NULL)
tmp->prev->next = *shaker;
else
*list = *shaker;
(*shaker)->next = tmp;
tmp->prev = *shaker;
*shaker = tmp;
}