-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-insertion_sort_list.c
48 lines (44 loc) · 1.13 KB
/
1-insertion_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
#include "sort.h"
/**
* swap_nodes - Swap two nodes in a listint_t doubly-linked list.
* @h: A pointer to the head of the doubly-linked list.
* @n1: A pointer to the first node to swap.
* @n2: The second node to swap.
*/
void swap_nodes(listint_t **h, listint_t **n1, listint_t *n2)
{
(*n1)->next = n2->next;
if (n2->next != NULL)
n2->next->prev = *n1;
n2->prev = (*n1)->prev;
n2->next = *n1;
if ((*n1)->prev != NULL)
(*n1)->prev->next = n2;
else
*h = n2;
(*n1)->prev = n2;
*n1 = n2->prev;
}
/**
* insertion_sort_list - Sorts a doubly linked list of integers
* using the insertion sort algorithm.
* @list: A pointer to the head of a doubly-linked list of integers.
*
* Description: Prints the list after each swap.
*/
void insertion_sort_list(listint_t **list)
{
listint_t *iter, *insert, *tmp;
if (list == NULL || *list == NULL || (*list)->next == NULL)
return;
for (iter = (*list)->next; iter != NULL; iter = tmp)
{
tmp = iter->next;
insert = iter->prev;
while (insert != NULL && iter->n < insert->n)
{
swap_nodes(list, &insert, iter);
print_list((const listint_t *)*list);
}
}
}