我用C语言编写了一个递归快速排序实现,我想使用STACK将其转换为迭代实现.
这是我用C:
int random_partition(int* arr, int start, int end) {
srand(time(NULL));
int random_pivot = rand() % (start - end) + start;
swap(&arr[random_pivot], &arr[end]);
int pivot = arr[end], pivot_index = start;
for (int i = start; i < end; i++) {
if (arr[i] <= pivot) {
swap(&arr[pivot_index], &arr[i]);
pivot_index++;
}
}
swap(&arr[pivot_index], &arr[end]);
return pivot_index;
}
void quick_sort(int* arr, int start, int end) {
if (start < end) {
int pivot_index = random_partition(arr, start, end);
quick_sort(arr, start, pivot_index - 1);
quick_sort(arr, pivot_index + 1, end);
}
}
这是我做的事情,但在弹出的时候我什么都不做,因为在递归中S我们做的是什么.
void quick_sort_iter(int* arr, int start, int end) {
stack* s = create_stack(n);
int pivot_index = random_partition(arr, start, end);
int p = pivot_index;
while (start < pivot_index) {
pivot_index = random_partition(arr, start, end);
push(s, start);
push(s, pivot_index--);
}
pivot_index = p;
while (pivot_index < end) {
push(s, pivot_index++);
push(s, end);
pivot_index = random_partition(arr, start, end);
}
while(!is_empty(s)) {
int e = pop(s);
int s = pop(s);
// do nothing, because in recursion the return doesn't do anything
}
return arr;
}
我首先想问的是,这是不是一条正确的道路,或者如何接近这一点?