/* 非递归栈实现快排 */
#include <stdio.h>
#include <math.h>>
#include <malloc.h>
#include <windows.h>
typedef struct _Stack
{
int *data;
int top;
}Stack;
/* 一次快排的结果,返回基准的位置 */
int OneQuickSort(int *arr, int i, int j)
{
//②if(j - i < 1) return -1;
int tmp = arr[i]; //基准
while( i < j )
{
while( i < j )
{
if(arr[j] < tmp) break;
j--;
}
arr[i] = arr[j]; //向前移动
while(i < j)
{
if(arr[i] > tmp) break;
i++;
}
arr[j] = arr[i]; //向后移动
}
arr[i] = tmp; //j == i
return i;
}
void QuickSort(int *arr, int left, int right)
{
Stack st;
//栈的长度最长不超过 log2(n)
int size = (int)log10(right-left+1)/log10(2.0);
size = (size+1)*sizeof(int);
st.data = (int*)malloc(size);
st.top = 0;
//入栈
st.data[st.top++] = left;
st.data[st.top++] = right;
//循环模拟递归
while(st.top != 0)
{
/* 出栈 快排 */
right = st.data[--st.top];
left = st.data[--st.top];
int mod = OneQuickSort(arr, left, right);
//与基准的紧挨着,为有序状态
if(mod - left > 1) //②if(mid != -1)
{
st.data[st.top++] = left;
st.data[st.top++] = mod - 1;
}
if(right - mod > 1)
{
st.data[st.top++] = mod + 1;
st.data[st.top++] = right;
}
}
free(st.data);
}
测试
int main()
{
int arr[] = {1,54,6,6,748,768,7,64,6379,76,78,746,7,64};
QuickSort(arr, 0, sizeof(arr)/sizeof(arr[0]) - 1);
int len = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i < len; i++)
{
printf("%d ",arr[i]);
}
system("pause");
return 0;
}
截图: