/*
* Copyright 2014 YU Heng-yang. All rights reserved.
*
* quick_sort_nonrecursive.c - Non-recursive quick sort implementation.
*
* Modify MAX_DEPTH to a larger number if large
* input is expected.
*
* 2014-7-8 YU Heng-yang.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "common.h"
void quick_sort(int *arr, int n);
int main(int argc, char *argv[])
{
int *array, n;
n = input(&array);
quick_sort(array, n);
output(array, n);
return 0;
}
#define MAX_DEPTH 1000
struct Interval {
int *base;
int n;
} stack[MAX_DEPTH + 1];
int top = -1;
void push(int *base, int n)
{
assert(top < MAX_DEPTH + 1);
stack[++top].base = base;
stack[top].n = n;
}
void pop(int **base, int *n)
{
assert(top > -1);
*base = stack[top].base;
*n = stack[top--].n;
}
void quick_sort(int *arr, int n)
{
int i, j, *base, k;
push(arr, n);
while (top != -1) {
pop(&base, &k);
if (k < 2)
continue;
i = 0;
j = k;
do {
/* choose base[0] as the pivot is not very good */
do ++i; while (i < j && base[i] < base[0]);
do --j; while (base[j] > base[0]);
if (i < j)
swap(base, i, j);
} while (i < j);
swap(base, 0, j);
push(base, j); /* quick_sort(base, j); */
push(base + j + 1, k - j - 1); /* quick_sort(base+j+1, n-j-1); */
}
}
快速排序3——非递归实现
最新推荐文章于 2023-04-09 20:04:43 发布