1. 程式人生 > >排序演算法之快速排序的非遞迴實現

排序演算法之快速排序的非遞迴實現

在之前的部落格中提到過快速排序的三種實現方式,不過都是通過遞迴來實現,今天我們將會利用棧來實現快速排序。

-----------------------------------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;
}