Skip to content

Commit 25c9fe5

Browse files
committed
sorting_algorithms
1 parent c2017e6 commit 25c9fe5

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

100-shell_sort.c

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include "sort.h"
2+
3+
/**
4+
* swap - Function that swaps two values
5+
*
6+
* @a: Fisrt value
7+
* @b: Second value
8+
* Return: 0
9+
*/
10+
void swap(int *a, int *b)
11+
{
12+
int tmp;
13+
14+
tmp = *b;
15+
*b = *a;
16+
*a = tmp;
17+
}
18+
19+
/**
20+
* gap_sort - sort array with gaps
21+
* @array: array to be sorted
22+
* @size: size of array
23+
* @gap: gap size
24+
*/
25+
void gap_sort(int *array, size_t size, unsigned int gap)
26+
{
27+
size_t j, k;
28+
29+
for (j = gap; j < size; j++)
30+
{
31+
k = j;
32+
while (k >= gap && array[k] < array[k - gap])
33+
{
34+
swap(array + k, array + k - gap);
35+
k -= gap;
36+
}
37+
}
38+
}
39+
40+
/**
41+
* shell_sort - shell sort
42+
* @array: array to be sorted
43+
* @size: size of array
44+
*/
45+
void shell_sort(int *array, size_t size)
46+
{
47+
unsigned int gap = 1;
48+
49+
while (gap < size / 3)
50+
gap = gap * 3 + 1;
51+
52+
while (gap >= 1)
53+
{
54+
gap_sort(array, size, gap);
55+
gap = (gap - 1) / 3;
56+
print_array(array, size);
57+
}
58+
}

main/100-main.c

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include "sort.h"
4+
5+
/**
6+
* main - Entry point
7+
*
8+
* Return: Always 0
9+
*/
10+
int main(void)
11+
{
12+
int array[] = {19, 48, 99, 71, 13, 52, 96, 73, 86, 7};
13+
size_t n = sizeof(array) / sizeof(array[0]);
14+
15+
print_array(array, n);
16+
printf("\n");
17+
shell_sort(array, n);
18+
printf("\n");
19+
print_array(array, n);
20+
return (0);
21+
}

output/shell

16.6 KB
Binary file not shown.

0 commit comments

Comments
 (0)