-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.c
92 lines (83 loc) · 2.49 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abertran <abertran@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/23 19:01:19 by abertran #+# #+# */
/* Updated: 2023/03/10 12:06:38 by abertran ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/* Pushes all the elements of stack a into stack b, except the three last.
Smaller values first, then the larger values to help with efficiency.*/
static void push_init(t_stack **stack_a, t_stack **stack_b)
{
int stack_size;
int pushes;
int i;
stack_size = get_stack_size(*stack_a);
pushes = 0;
i = 0;
while (stack_size > 6 && i < stack_size && pushes < stack_size / 2)
{
if ((*stack_a)->index <= stack_size / 2)
{
do_pb(stack_a, stack_b);
pushes++;
}
else
do_ra(stack_a);
i++;
}
while (stack_size - pushes > 3)
{
do_pb(stack_a, stack_b);
pushes++;
}
}
/* The stack a is almost sorted, rotate stack a until the lowest
value is at the top. If it is in the bottom half of the stack, reverse
rotate, otherwise rotate until it is at the top. */
static void sort_stack(t_stack **stack_a)
{
int lowest_p;
int stack_size;
stack_size = get_stack_size(*stack_a);
lowest_p = position_lowest_index(stack_a);
if (lowest_p > stack_size / 2)
{
while (lowest_p < stack_size)
{
do_rra(stack_a);
lowest_p++;
}
}
else
{
while (lowest_p > 0)
{
do_ra(stack_a);
lowest_p--;
}
}
}
/* Sorting algorithm for a stack larger than 3.
Push everything but 3 numbers to stack B.
Sort the 3 numbers left in stack A.
Calculate the most cost-effective move.
Shift elements until stack A is in order. */
void sort(t_stack **stack_a, t_stack **stack_b)
{
push_init(stack_a, stack_b);
sort_three(stack_a);
while (*stack_b)
{
get_target_position(stack_a, stack_b);
cost(stack_a, stack_b);
cheapest_move(stack_a, stack_b);
}
if (!is_sorted(*stack_a))
sort_stack(stack_a);
}