-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.c
104 lines (95 loc) · 2.11 KB
/
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yenoh <yenoh@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/13 12:36:35 by yenoh #+# #+# */
/* Updated: 2023/11/13 22:32:47 by yenoh ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int get_stack_idx(t_stack *stack, int n)
{
t_node *tmp;
int i;
tmp = stack->head;
i = 0;
while (tmp && tmp->num != n)
{
tmp = tmp->next;
i++;
}
return (i);
}
int set_rotate(t_ps *ps, int i, int chunk)
{
int min;
int max;
int j;
int t;
max = 0;
min = ps->a->len;
j = i - 1;
while (++j <= i + chunk)
{
t = get_stack_idx(ps->a, j);
if (t < min)
min = t;
if (t > max)
max = t;
}
if (min < ps->a->len - max)
return (1);
return (0);
}
void a_to_b(t_ps *ps, int i, int chunk)
{
while (ps->a->len > 0)
{
if (ps->a->head->num <= i)
{
cmd_update(ps, 4, pb);
i++;
}
else if (ps->a->head->num > i && ps->a->head->num <= i + chunk)
{
cmd_update(ps, 4, pb);
cmd_update(ps, 6, rb);
i++;
}
else
{
if (set_rotate(ps, i, chunk))
cmd_update(ps, 5, ra);
else
cmd_update(ps, 8, rra);
}
}
}
void max_to_top(t_ps *ps)
{
int max;
int max_idx;
max = get_max(ps->b);
max_idx = get_stack_idx(ps->b, max);
if (max_idx < ps->b->len / 2)
{
while (ps->b->head->num != max)
cmd_update(ps, 6, rb);
}
else
{
while (ps->b->head->num != max)
cmd_update(ps, 9, rrb);
}
}
void b_to_a(t_ps *ps)
{
while (ps->b->len > 0)
{
max_to_top(ps);
cmd_update(ps, 3, pa);
}
}