Skip to content
Snippets Groups Projects
Commit eac58de0 authored by Florian Burgener's avatar Florian Burgener
Browse files

Refactoring 2

parent 8a391167
No related branches found
No related tags found
No related merge requests found
...@@ -14,31 +14,29 @@ ...@@ -14,31 +14,29 @@
#include "stack.h" #include "stack.h"
void pop_left_push_right(stack *left_stack, stack *right_stack, int current_value) { typedef enum _sort_behavior {
behavior_lower,
behavior_higher,
behavior_none,
} sort_behavior;
void pop_left_push_right(stack *left_stack, stack *right_stack, int current_value, sort_behavior sb) {
while (!stack_is_empty(*left_stack)) { while (!stack_is_empty(*left_stack)) {
int tmp; int tmp;
stack_peek(*left_stack, &tmp); stack_peek(*left_stack, &tmp);
if (sb == behavior_lower) {
if (current_value < tmp) { if (current_value < tmp) {
break; break;
} }
} else if (sb == behavior_higher) {
stack_pop(left_stack, &tmp);
stack_push(right_stack, tmp);
}
}
void pop_right_push_left(stack *right_stack, stack *left_stack, int current_value) {
while (!stack_is_empty(*right_stack)) {
int tmp;
stack_peek(*right_stack, &tmp);
if (current_value > tmp) { if (current_value > tmp) {
break; break;
} }
}
stack_pop(right_stack, &tmp); stack_pop(left_stack, &tmp);
stack_push(left_stack, tmp); stack_push(right_stack, tmp);
} }
} }
...@@ -50,19 +48,15 @@ void sort_array(int *array, int array_length) { ...@@ -50,19 +48,15 @@ void sort_array(int *array, int array_length) {
for (int i = 0; i < array_length; i += 1) { for (int i = 0; i < array_length; i += 1) {
// Pop values from left stack to right stack. // Pop values from left stack to right stack.
pop_left_push_right(&left_stack, &right_stack, array[i]); pop_left_push_right(&left_stack, &right_stack, array[i], behavior_lower);
// Pop values from right stack to left stack. // Pop values from right stack to left stack.
pop_right_push_left(&right_stack, &left_stack, array[i]); pop_left_push_right(&right_stack, &left_stack, array[i], behavior_higher);
// Push to left stack. // Push to left stack.
stack_push(&left_stack, array[i]); stack_push(&left_stack, array[i]);
} }
// Until right stack is empty pop value from right stack and push it to left stack. // Until right stack is empty pop value from right stack and push it to left stack.
while (!stack_is_empty(right_stack)) { pop_left_push_right(&right_stack, &left_stack, 0, behavior_none);
int tmp;
stack_pop(&right_stack, &tmp);
stack_push(&left_stack, tmp);
}
// Until the left stack is empty, pop the value and place it in the array. // Until the left stack is empty, pop the value and place it in the array.
for (int i = 0; i < array_length; i += 1) { for (int i = 0; i < array_length; i += 1) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment