Skip to content

Commit c2017e6

Browse files
committed
sorting_algorithms
1 parent c8a003e commit c2017e6

File tree

5 files changed

+125
-0
lines changed

5 files changed

+125
-0
lines changed

3-O

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
O(nlog(n))
2+
O(nlog(n))
3+
O(n^2)

3-quick_sort.c

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#include "sort.h"
2+
3+
/**
4+
* quick_sort - Function that sorts an array based on
5+
* quick sort algorithm
6+
* @array: Array to be sorted
7+
* @size: Size of array
8+
* Return: 0
9+
*/
10+
void quick_sort(int *array, size_t size)
11+
{
12+
size_t pivot;
13+
14+
if (!array || size < 2)
15+
return;
16+
17+
print_sort(array, size, 1);
18+
19+
/* partition and get pivot index */
20+
pivot = partition(array, size);
21+
22+
/* repeat for left of index */
23+
quick_sort(array, pivot);
24+
/* repeat for index and right */
25+
quick_sort(array + pivot, size - pivot);
26+
}
27+
28+
/**
29+
* swap - Function that swaps two values
30+
*
31+
* @a: Fisrt value
32+
* @b: Second value
33+
* Return: 0
34+
*/
35+
void swap(int *a, int *b)
36+
{
37+
int tmp;
38+
39+
tmp = *b;
40+
*b = *a;
41+
*a = tmp;
42+
}
43+
44+
/**
45+
* partition - Function that sets the pivot for quick_sort
46+
*
47+
* @array: Array to partition
48+
* @size: Size of array
49+
* Return: (i + 1)
50+
*/
51+
size_t partition(int array[], size_t size)
52+
{
53+
int pivot;
54+
size_t i = -1;
55+
size_t j;
56+
57+
if (!array || size < 2)
58+
return (0);
59+
60+
pivot = array[size - 1];
61+
62+
for (j = 0; j < size - 1; j++)
63+
{
64+
if (array[j] <= pivot)
65+
{
66+
i++;
67+
if (i != j)
68+
{
69+
swap(&array[i], &array[j]);
70+
print_sort(array, size, 0);
71+
}
72+
}
73+
}
74+
if (i + 1 != size - 1)
75+
{
76+
swap(&array[i + 1], &array[size - 1]);
77+
print_sort(array, size, 0);
78+
}
79+
return (i + 1);
80+
}
81+
82+
/**
83+
* print_sort - Function that prints as it should
84+
* @array: Array to be printed
85+
* @size: Size of array
86+
* @init: Should initialize array
87+
* Return: 0
88+
*/
89+
void print_sort(int array[], size_t size, int init)
90+
{
91+
static int *p = (void *)0;
92+
static size_t s;
93+
94+
if (!p && init)
95+
{
96+
p = array;
97+
s = size;
98+
}
99+
if (!init)
100+
print_array(p, s);
101+
}

2-main.c renamed to main/2-main.c

File renamed without changes.

main/3-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+
quick_sort(array, n);
18+
printf("\n");
19+
print_array(array, n);
20+
return (0);
21+
}

output/quick

16.7 KB
Binary file not shown.

0 commit comments

Comments
 (0)