-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_sort.c
87 lines (82 loc) · 1.89 KB
/
quick_sort.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* quick_sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akhossan <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/03 22:18:23 by akhossan #+# #+# */
/* Updated: 2019/12/03 22:40:57 by akhossan ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static int sum(t_stack *a, int depth)
{
int sum;
sum = 0;
while (a && depth--)
{
sum += a->nbr;
a = a->next;
}
return (sum);
}
void quick_sort(t_stack **a, t_stack **temp, int n)
{
int toplen;
int median;
int i;
static int it;
t_stack *node;
if (n == 1)
return ;
toplen = 0;
median = sum(*a, n) / n;// dummy median (fix later);
i = 0;
while (i < n)
{
if ((*a)->nbr <= median)// store the smaller half in b stack;
{
node = pop(a);
push(temp, node->nbr);
it++;
free(node);
toplen++;
}
else
{
rotate(a);
it++;
}
i++;
}
i = -1;
while (++i < n - toplen)
{
rrotate(a);
it++;
}
i = 0;
while (i++ < toplen)
{
node = pop(temp);
push(a, node->nbr);
it++;
free(node);
}
quick_sort(a, temp, toplen);//recursive call on smaller half.
i = -1;
while (++i < toplen)
{
it++;
rotate(a);
}
quick_sort(a, temp, n - toplen);//recursive call on larger half
i = -1;
while (++i < toplen)
{
it++;
rrotate(a);
}
printf("it: %d\n", it);
}