用纯C语言实现快速排序，分递归调用法和非递归调用法。

c 专栏收录该内容
2 篇文章 0 订阅

#include <stdlib.h>

#include <stdio.h>

//先用纯C语言实现一个简单的栈
#define     STATCK_SIZE      8
int stack[STATCK_SIZE] = {0};
int nTop = 0;

int push(int value)
{
if(nTop < STATCK_SIZE)
{
stack[nTop] = value;
nTop++;
return nTop;
}
else
{
return -1;
}
}

int pop()
{
if(nTop < 1)
{
return -1;
}
else
{
int tmp = stack[nTop-1];
nTop--;
return tmp;
}
}

int empty()
{
return (nTop > 0?0:1);
}

int partition(int* vec,int low,int high)
{
int sentry=vec[low];  //选第一个元素作为哨兵
while(low<high)
{
while(low<high && vec[high]>=sentry)
high--;
vec[low]=vec[high];

while(low<high && vec[low]<=sentry)
low++;
vec[high]=vec[low];
}

vec[low]=sentry;
return low;
}

//递归调用法
void quicksort1(int* vec,int low,int high){
if(low<high){
int mid=partition(vec,low,high);
quicksort1(vec,low,mid-1);
quicksort1(vec,mid+1,high);
}
}

//在单片开发栈资源非常有限，不易采用递归调用。

void quicksort2(int* vec,int low,int high){
if(low<high)
{
int mid=partition(vec,low,high);
if(low<mid-1){
push(low);
push(mid-1);
}

if(mid+1<high){
push(mid+1);
push(high);
}
//用栈保存未排段首尾
while(!empty())
{
int high2=pop();
int low2=pop();
mid=partition(vec,low2,high2);
if(low2<mid-1){
push(low2);
push(mid-1);
}
if(mid+1<high2){
push(mid+1);
push(high2);
}
}
}
}

int main()
{
int i;
int a[8] = {8,7,6,5,4,3,2,1};
//quicksort1(a, 0, 7);
quicksort2(a, 0, 7);

for(i=0;i<8;i++)
printf("%d,", a[i]);
// getchar(); //便于调试
return 0;
}
• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

10-04

03-31 1568
09-25 7001
04-10 87
05-07 388
10-11 531
02-25 2109
10-30 570
07-24 1万+
06-02 368
11-03 109
11-27 1183
07-02 1万+
01-01 758
04-01 1447