53 lines
1.8 kB
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* sort_insert.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: ohaponiu <marvin@42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2026/04/30 09:05:54 by ohaponiu #+# #+# */
9/* Updated: 2026/05/03 22:20:00 by ohaponiu ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "operations.h"
14#include "stack.h"
15#include "strategies.h"
16
17/* push elements that break ascending order to B, keep sorted tail in A */
18static void push_unsorted(t_stack *a, t_stack *b, t_ops *ops)
19{
20 int n;
21 int i;
22 int max_seen;
23
24 n = stack_size(a);
25 max_seen = stack_at(a, 0);
26 i = -1;
27 while (++i < n)
28 {
29 if (stack_at(a, 0) >= max_seen)
30 {
31 max_seen = stack_at(a, 0);
32 op_ra(a, ops);
33 }
34 else
35 op_pb(a, b, ops);
36 }
37}
38
39/* insertion sort: push unsorted to B, insert each back at correct position */
40void sort_insert(t_stack *a, t_stack *b, t_ops *ops)
41{
42 if (stack_is_sorted(a))
43 return ;
44 if (stack_size(a) <= 5)
45 return (sort_five(a, b, ops));
46 push_unsorted(a, b, ops);
47 while (!stack_is_empty(b))
48 {
49 rotate_a_to_top(a, find_insert_pos(a, stack_at(b, 0)), ops);
50 op_pa(a, b, ops);
51 }
52 rotate_a_to_top(a, find_extremum_pos(a, 0), ops);
53}