非递归写法
利用栈
主要需要记录起始和结尾即low和high 的值,用循环只能处理一边,所以需要将temp后面的起始和结尾下标记录下来。利用栈来记录(也可以使用队列)。
先将下标进栈:0,3,5,7;
先判断栈为不为空,不空说明还有未处理完的数对;
代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
int Partition(int *arr, int low, int high)
{
int temp = arr[low];
while(low < high)
{
while((low < high)&&(arr[high] >= temp))
{
high--;
}
if(low == high)
{
break;
}
else
{
arr[low] = arr[high];
}
while((low < high)&&(arr[low] <= temp))
{
low++;
}
if(low == high)
{
break;
}
else
{
arr[high] = arr[low];
}
}
arr[low] = temp;
return low;
}
void QuickSort(int *arr, int len)
{
int tmp = (int)ceil((log((double)len)/log((double)2)));//ceil向上取整,返回值为double类型
//int *stack = (int *)malloc(sizeof(int)*2*(int)(log((double)len)/log((double)2)));//未向上取整
int *stack = (int *)malloc(sizeof(int)*2*tmp);
assert(stack != NULL);
int top = 0;//栈顶指针,下标可取
int low = 0;
int high = len-1;
int par = Partition(arr,low,high);
if(par > low+1)//保证左边至少有两个数字
{
stack[top++] = low;//保存起始
stack[top++] = par-1;//保存结尾
}
if(par < high-1)//保证右边至少有两个数字
{
stack[top++] = par+1;
stack[top++] = high;
}
while(top > 0)
{
high = stack[--top];
low = stack[--top];
par = Partition(arr,low,high);
if(par > low+1)//保证左边至少有两个数字
{
stack[top++] = low;//保存起始
stack[top++] = par-1;//保存结尾
}
if(par < high-1)
{
stack[top++] = par+1;
stack[top++] = high;
}
}
free(stack);
}
void Show(int *arr,int len)
{
for(int i=0; i<len; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {32,2334,35,56,68,856,34,33};
QuickSort(arr,sizeof(arr)/sizeof(arr[0]));
Show(arr,sizeof(arr)/sizeof(arr[0]));
return 0;
}