Push_swap/sorting.c
2022-01-17 16:20:46 +01:00

129 lines
3.0 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sorting.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/07 19:14:03 by apommier #+# #+# */
/* Updated: 2022/01/07 19:14:03 by apommier ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
t_list *swap(t_list *a, t_list **b, t_slist **action, t_list *to_swap)
{
int place_for_b;
int place;
t_list *start_b;
start_b = *b;
place = 0;
while ((*b)->index != to_swap->index)
{
place++;
*b = (*b)->next;
}
start_b = make_list(place, start_b, *action, 'b');
place_for_b = find_place_for_b(a, to_swap->index, ft_lstsize(start_b));
a = make_list(place_for_b, a, *action, 'a');
*b = ft_pa(&a, &start_b, action);
return (a);
}
t_list *make_list(int place, t_list *list, t_slist *action, char type)
{
int lstsize;
lstsize = ft_lstsize(list);
if (place > lstsize / 2)
{
while (lstsize - place)
{
ft_rra_rrb(&list, &action, type);
place++;
}
}
else
{
while (place)
{
ft_ra_rb(&list, &action, type);
place--;
}
}
return (list);
}
t_list *swap_to_a(t_list *a, t_list *b, t_list *start_b, t_slist *action)
{
int lst_size;
int size_b;
int move;
int best_move;
t_list *to_swap;
to_swap = 0;
size_b = ft_lstsize(b);
move = size_b + ft_lstsize(a);
best_move = move;
lst_size = size_b;
while (lst_size)
{
best_move = ft_lstsize(a) + ft_lstsize(b);
b = start_b;
to_swap = best_b(&b, start_b, a, best_move);
a = swap(a, &start_b, &action, to_swap);
lst_size--;
}
return (a);
}
int find_place_for_b(t_list *list, int index, int size_b)
{
int count;
int save_index;
t_list *start;
start = list;
save_index = ft_lstsize(list) + size_b;
count = 0;
while (list)
{
if (list->index > index && list->index < save_index)
save_index = list->index;
list = list->next;
}
while (start->index != save_index)
{
count++;
start = start->next;
}
return (count);
}
int find_nbr(int size_b, t_list *a, t_list *b, int index_b)
{
int move;
int place;
int size_a;
size_a = ft_lstsize(a);
place = 1;
move = 0;
while (b->index != index_b)
{
place++;
b = b->next;
}
move = find_place_for_b(a, b->index, size_b);
if (move > size_a / 2)
move = size_a - move;
if (place > size_b / 2)
move += size_b - place;
else
move += place;
return (move);
}