summaryrefslogtreecommitdiff
path: root/sorting.c
blob: a682280e6b88890b8d29b0e402d7e18410e2e710 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   sorting.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: dkaiser <dkaiser@student.42heilbronn.de    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/04/13 15:04:19 by dkaiser           #+#    #+#             */
/*   Updated: 2024/04/17 11:50:56 by dkaiser          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "push_swap.h"

static void presort(t_psdata *data)
{
    int size;
    int pivot;
    int max;

    size = data->a->size;
    pivot = size / 2;
    max = data->a->stack[0];
    while (size--)
    {
        if (data->a->stack[0] < max)
        {
            run_command(data, PB);
            if (data->b->stack[0] > pivot)
                run_command(data, RB);
        }
        else
        {
            max = data->a->stack[0];
            run_command(data, RA);
        }
    }
}

static int calculate_score(t_psdata *data, int pos)
{
    int moves_to_top;
    int moves_to_spot;
    int i;

    if (pos < (data->b->size + 1) / 2)
        moves_to_top = pos;
    else
        moves_to_top = data->b->size - pos;
    i = 0;
    while (i < data->a->size && data->a->stack[i] < data->b->stack[pos])
        i++;
    if (i < (data->a->size + 1) / 2)
        moves_to_spot = 2 * i + 1;
    else
        moves_to_spot = 2 * ((data->a->size - i) + 1);
    return moves_to_top + moves_to_spot;
}

static void move_to_right_spot(t_psdata *data, int idx)
{

}

static void scoresort(t_psdata *data)
{
    int *scores;
    int i;
    int min_score;

    scores = malloc(sizeof(int) * data->b->size);
    // Error if allocation fails
    i = 0;
    while (i < data->b->size)
    {
        scores[i] = calculate_score(data, i);
        i++;
    }
    i = 0;
    min_score = 0;
    while (i < data->b->size)
    {
        if (scores[i] < scores[min_score])
            min_score = i;
        i++;
    }
    move_to_right_spot(data, min_score);

    free(scores);
    if (data->b->size > 0)
        scoresort(data);
}

void stack_sort(t_psdata *data)
{
    presort(data);
    scoresort(data);
}