File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ O(n)
2
+ O(n^2)
3
+ O(n^2)
Original file line number Diff line number Diff line change
1
+ #include "sort.h"
2
+
3
+ /**
4
+ * swap_nodes - Swap two nodes in a listint_t doubly-linked list.
5
+ * @h: A pointer to the head of the doubly-linked list.
6
+ * @n1: A pointer to the first node to swap.
7
+ * @n2: The second node to swap.
8
+ */
9
+ void swap_nodes (listint_t * * h , listint_t * * n1 , listint_t * n2 )
10
+ {
11
+ (* n1 )-> next = n2 -> next ;
12
+ if (n2 -> next != NULL )
13
+ n2 -> next -> prev = * n1 ;
14
+ n2 -> prev = (* n1 )-> prev ;
15
+ n2 -> next = * n1 ;
16
+ if ((* n1 )-> prev != NULL )
17
+ (* n1 )-> prev -> next = n2 ;
18
+ else
19
+ * h = n2 ;
20
+ (* n1 )-> prev = n2 ;
21
+ * n1 = n2 -> prev ;
22
+ }
23
+
24
+ /**
25
+ * insertion_sort_list - Sorts a doubly linked list of integers
26
+ * using the insertion sort algorithm.
27
+ * @list: A pointer to the head of a doubly-linked list of integers.
28
+ *
29
+ * Description: Prints the list after each swap.
30
+ */
31
+ void insertion_sort_list (listint_t * * list )
32
+ {
33
+ listint_t * iter , * insert , * tmp ;
34
+
35
+ if (list == NULL || * list == NULL || (* list )-> next == NULL )
36
+ return ;
37
+
38
+ for (iter = (* list )-> next ; iter != NULL ; iter = tmp )
39
+ {
40
+ tmp = iter -> next ;
41
+ insert = iter -> prev ;
42
+ while (insert != NULL && iter -> n < insert -> n )
43
+ {
44
+ swap_nodes (list , & insert , iter );
45
+ print_list ((const listint_t * )* list );
46
+ }
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments