summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDominik Kaiser2024-04-16 00:01:47 +0200
committerDominik Kaiser2024-04-16 00:01:47 +0200
commitf421b2dcf9a5d12655e48f4a06f35f17e785fb0f (patch)
treefd27f598757f59db733079b9facc693b6c3ec5c8
parent05e786db0ae74da69012e1b5aa2dc9169e56723b (diff)
downloadpush_swap-f421b2dcf9a5d12655e48f4a06f35f17e785fb0f.tar.gz
push_swap-f421b2dcf9a5d12655e48f4a06f35f17e785fb0f.zip
Add inefficient quicksort? algorithm
This algorithm is based on quicksort but probably not really in its spirit. It is extremely inefficient but could maybe fixed with some post-optimization.
-rw-r--r--main.c12
-rw-r--r--sorting.c44
2 files changed, 48 insertions, 8 deletions
diff --git a/main.c b/main.c
index 803f6eb..076688b 100644
--- a/main.c
+++ b/main.c
@@ -6,7 +6,7 @@
/* By: dkaiser <dkaiser@student.42heilbronn.de +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/12 17:03:30 by dkaiser #+# #+# */
-/* Updated: 2024/04/15 17:53:19 by dkaiser ### ########.fr */
+/* Updated: 2024/04/15 23:41:34 by dkaiser ### ########.fr */
/* */
/* ************************************************************************** */
@@ -39,11 +39,11 @@ int main(int argc, char *argv[])
stack_b->size = 0;
stack_optimize(stack_a);
pscmds = stack_sort(stack_a, stack_b);
- /* optimize_commands(&pscmds); */
+ optimize_commands(&pscmds);
print_commands(pscmds);
- ft_printf("\nA: ");
- stack_print(stack_a);
- ft_printf("B: ");
- stack_print(stack_b);
+ /* ft_printf("\nA: "); */
+ /* stack_print(stack_a); */
+ /* ft_printf("B: "); */
+ /* stack_print(stack_b); */
return (0);
}
diff --git a/sorting.c b/sorting.c
index f04304f..b5668a9 100644
--- a/sorting.c
+++ b/sorting.c
@@ -6,14 +6,54 @@
/* By: dkaiser <dkaiser@student.42heilbronn.de +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/13 15:04:19 by dkaiser #+# #+# */
-/* Updated: 2024/04/15 17:54:23 by dkaiser ### ########.fr */
+/* Updated: 2024/04/15 23:39:57 by dkaiser ### ########.fr */
/* */
/* ************************************************************************** */
+#include "libft/ft_printf.h"
+#include "libft/libft.h"
#include "push_swap.h"
+int is_sorted(t_stack *stack)
+{
+ int i;
+
+ if (stack->size < 2)
+ return 1;
+ i = 1;
+ while (i < stack->size)
+ {
+ if (stack->stack[i] < stack->stack[i-1])
+ return 0;
+ i++;
+ }
+ return 1;
+}
+
t_list *stack_sort(t_stack *stack_a, t_stack *stack_b)
{
- return NULL;
+ t_list *cmds = NULL;
+ int pivot;
+
+ int pivot_idx = stack_a->size - 1;
+ while (stack_b->size || !is_sorted(stack_a))
+ {
+ pivot = stack_a->stack[pivot_idx];
+
+ while (stack_a->size > 0 && stack_a->stack[0] != pivot)
+ {
+ if (stack_a->stack[0] > pivot)
+ run_command(stack_a, stack_b, &cmds, RA);
+ else
+ run_command(stack_a, stack_b, &cmds, PB);
+ }
+ while (stack_b->size > 0)
+ run_command(stack_a, stack_b, &cmds, PA);
+ if (stack_a->stack[pivot_idx] == pivot)
+ pivot_idx--;
+ if (pivot_idx < 0)
+ pivot_idx = stack_a->size - 1;
+ }
+ return cmds;
}