在之前的博客中提到过快速排序的三种实现方式,不过都是通过递归来实现,今天我们将会利用栈来实现快速排序。
-----------------------------------Stack.h-------------------------------------------
//栈的实现
#pragma once
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 20
typedef int DataType;
typedef struct Stack
{
DataType _arr[MAXSIZE];
int _top;
}Stack;
void InitStack(Stack* ps)
{
assert(ps);
ps->_top = 0;
}
void PrintStack(Stack* ps)
{
assert(ps);
int i = 0;
for (; i < ps->_top; i++)
{
printf("%d ", ps->_arr[i]);
}
printf("\n");
}
void PushStack(Stack* ps, DataType d)
{
assert(ps);
ps->_arr[ps->_top++] = d;
if (MAXSIZE == ps->_top)
return;
}
void PopStack(Stack* ps)
{
assert(ps);
if (StackEmpty(ps))
return;
ps->_top--;
}
int StackEmpty(Stack* ps)
{
assert(ps);
return 0 == ps->_top;
}
int StackSize(Stack* ps)
{
return ps->_top;
}
DataType StackTop(Stack* ps)
{
assert(ps);
return ps->_arr[ps->_top - 1];
}
-----------------------------------Sort.c--------------------------------------
//快排的实现
int exchange(int arr[], int beg, int end)
{
int key_value = arr[end];
int cur = beg;
int prev = cur - 1;
while (cur < end)
{
if (arr[cur] < key_value && ++prev != cur)
Swap(&arr[cur], &arr[prev]);
cur++;
}
if (++prev != end)
Swap(&arr[prev], &arr[end]);
return prev;
}
void QuickSortNor(int arr[], int size)
{
if (size <= 1)
return;
int left = 0;
int right = size;
Stack s;
InitStack(&s);
PushStack(&s, size-1);
PushStack(&s, 0);
while (!StackEmpty(&s))
{
left = StackTop(&s);
PopStack(&s);
right = StackTop(&s);
PopStack(&s);
if (left < right)
{
int boundary = exchange(arr,left,right); //找到基准值
PushStack(&s, right); //排左侧->将右侧部分压栈
PushStack(&s, boundary+1);
PushStack(&s, boundary-1); //排右侧->将左侧部分压栈
PushStack(&s, left);
}
}
}
-----------------------------------test.c---------------------------------------
//测试代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<Windows.h>
void test()
{
int arr[] = { 9,5,2,7,4,3,8,6 };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
QuickSortNor(arr, sz);
for (; i < sz; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
test();
system("pause");
return;
}