-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex_stack.c
More file actions
93 lines (88 loc) · 2.17 KB
/
index_stack.c
File metadata and controls
93 lines (88 loc) · 2.17 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* index_stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yetsabe <yetsabe@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/07/18 19:59:09 by yetsabe #+# #+# */
/* Updated: 2025/07/28 14:40:51 by yetsabe ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
// Copies the stack's values into a dynamic array
int *copy_stack_array(t_stack *a, int size)
{
int *array;
t_node *tmp;
int i;
array = malloc(sizeof(int) * size);
if (!array)
exit_error();
tmp = a->top;
i = 0;
while (i < size && tmp)
{
array[i] = tmp->value;
tmp = tmp->next;
i++;
}
return (array);
}
// Sorts an array using bubble sort (sufficient for 100 of 500 elements)
void sort_array(int *array, int size)
{
int i;
int j;
int tmp;
i = 0;
while (i < size - 1)
{
j = 0;
while (j < size - i - 1)
{
if (array[j] > array[j + 1])
{
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
j++;
}
i++;
}
}
// Replaces stack values with their corresponding sorted indices
void replace_values_by_indices(t_stack *a, int *array, int size)
{
t_node *tmp;
int i;
tmp = a->top;
while (tmp)
{
i = 0;
while (i < size)
{
if (tmp->value == array[i])
{
tmp->value = i;
break ;
}
i++;
}
tmp = tmp->next;
}
}
// Main function: transforms values into their corresponding indices.
void index_stack(t_stack *a)
{
int *array;
int size;
size = count_nodes(a);
if (size < 2)
return ;
array = copy_stack_array(a, size);
sort_array(array, size);
replace_values_by_indices(a, array, size);
free(array);
}