65 lines
2.0 kB
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* sort_chunk.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: ohaponiu <marvin@42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2026/05/01 09:04:23 by ohaponiu #+# #+# */
9/* Updated: 2026/05/04 12:50:58 by ohaponiu ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "operations.h"
14#include "stack.h"
15#include "strategies.h"
16#include <libft.h>
17
18/* push A to B in chunks sized by sqrt(n), smaller values rotate to bottom */
19static void push_chunks_to_b(t_stack *a, t_stack *b, t_ops *ops)
20{
21 int chunk;
22 int pushed;
23 int val;
24
25 chunk = ft_sqrt(stack_size(a)) * 14 / 10;
26 pushed = 0;
27 while (!stack_is_empty(a))
28 {
29 val = stack_at(a, 0);
30 if (val <= pushed)
31 {
32 op_pb(a, b, ops);
33 op_rb(b, ops);
34 pushed++;
35 }
36 else if (val <= pushed + chunk)
37 {
38 op_pb(a, b, ops);
39 pushed++;
40 }
41 else
42 op_ra(a, ops);
43 }
44}
45
46/* push B back to A by repeatedly moving max to top */
47static void push_back_to_a(t_stack *a, t_stack *b, t_ops *ops)
48{
49 while (!stack_is_empty(b))
50 {
51 rotate_b_to_top(b, find_extremum_pos(b, 1), ops);
52 op_pa(a, b, ops);
53 }
54}
55
56/* chunk sort: split into sqrt-sized ranges, push to B, pop max back */
57void sort_chunk(t_stack *a, t_stack *b, t_ops *ops)
58{
59 if (stack_is_sorted(a))
60 return ;
61 if (stack_size(a) <= 5)
62 return (sort_five(a, b, ops));
63 push_chunks_to_b(a, b, ops);
64 push_back_to_a(a, b, ops);
65}