Skip to content

Commit 8173808

Browse files
committed
sorting_algorithms
1 parent 44ef511 commit 8173808

File tree

4 files changed

+114
-0
lines changed

4 files changed

+114
-0
lines changed

1-insertion_sort_list.c

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include "sort.h"
2+
3+
/**
4+
* insertion_sort_list - perform insertion sort on a linked list
5+
* @list: head node of the linked list
6+
*/
7+
void insertion_sort_list(listint_t **list)
8+
{
9+
listint_t *current, *swap, *prv;
10+
11+
if (!list || !*list)
12+
return;
13+
14+
current = *list;
15+
while ((current = current->next))
16+
{
17+
swap = current;
18+
while (swap->prev && swap->n < swap->prev->n)
19+
{
20+
prv = swap->prev;
21+
if (swap->next)
22+
swap->next->prev = prv;
23+
if (prv->prev)
24+
prv->prev->next = swap;
25+
else
26+
*list = swap;
27+
prv->next = swap->next;
28+
swap->prev = prv->prev;
29+
swap->next = prv;
30+
prv->prev = swap;
31+
32+
print_list(*list);
33+
}
34+
}
35+
}

1-main.c

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include "sort.h"
4+
5+
/**
6+
* create_listint - Creates a doubly linked list from an array of integers
7+
*
8+
* @array: Array to convert to a doubly linked list
9+
* @size: Size of the array
10+
*
11+
* Return: Pointer to the first element of the created list. NULL on failure
12+
*/
13+
listint_t *create_listint(const int *array, size_t size)
14+
{
15+
listint_t *list;
16+
listint_t *node;
17+
int *tmp;
18+
19+
list = NULL;
20+
while (size--)
21+
{
22+
node = malloc(sizeof(*node));
23+
if (!node)
24+
return (NULL);
25+
tmp = (int *)&node->n;
26+
*tmp = array[size];
27+
node->next = list;
28+
node->prev = NULL;
29+
list = node;
30+
if (list->next)
31+
list->next->prev = list;
32+
}
33+
return (list);
34+
}
35+
36+
/**
37+
* main - Entry point
38+
*
39+
* Return: Always 0
40+
*/
41+
int main(void)
42+
{
43+
listint_t *list;
44+
int array[] = {19, 48, 99, 71, 13, 52, 96, 73, 86, 7};
45+
size_t n = sizeof(array) / sizeof(array[0]);
46+
47+
list = create_listint(array, n);
48+
if (!list)
49+
return (1);
50+
print_list(list);
51+
printf("\n");
52+
insertion_sort_list(&list);
53+
printf("\n");
54+
print_list(list);
55+
return (0);
56+
}

insertion

16.6 KB
Binary file not shown.

print_list.c

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include <stdio.h>
2+
#include "sort.h"
3+
4+
/**
5+
* print_list - Prints a list of integers
6+
*
7+
* @list: The list to be printed
8+
*/
9+
void print_list(const listint_t *list)
10+
{
11+
int i;
12+
13+
i = 0;
14+
while (list)
15+
{
16+
if (i > 0)
17+
printf(", ");
18+
printf("%d", list->n);
19+
++i;
20+
list = list->next;
21+
}
22+
printf("\n");
23+
}

0 commit comments

Comments
 (0)