非递归快速排序 C实现


前言

快速排序的非递归需要借助到栈,C语言没有提供,需要自己实现。



一、栈实现


Stack.h

#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef int DataType;

#define INCREMENT 2

typedef struct Stack
{
    
    
	DataType* arr;
	int top;
	int capacity;
}Stack;

void StackInit(Stack* stk,int sz);
void StackDestroy(Stack* stk);
void StackPush(Stack* stk,DataType val);
void StackPop(Stack* stk);
DataType StackTop(Stack* stk);
bool isEmpty(Stack* stk);
void CheckCapacity(Stack* stk);

Stack.c

#include "Stack.h"

void StackInit(Stack* stk, int sz)
{
    
    
	assert(stk);

	stk->arr = (DataType*)malloc(sizeof(DataType) * sz);
	if (!stk->arr)
	{
    
    
		printf("malloc fail\n");
		exit(-1);
	}

	stk->top = -1;
	stk->capacity = sz;
}

void StackDestroy(Stack* stk)
{
    
    
	assert(stk);
	free(stk->arr);
	stk->arr = NULL;
	stk->top = -1;
	stk->capacity = 0;
}


void StackPush(Stack* stk, DataType val)
{
    
    
	assert(stk);

	CheckCapacity(stk);

	stk->top++;
	stk->arr[stk->top] = val;
}

void StackPop(Stack* stk)
{
    
    
	if (isEmpty(stk))
		return;
	stk->top--;
}

DataType StackTop(Stack* stk) 
{
    
    
	assert(stk);
	if (isEmpty(stk))
		return -1;
	return stk->arr[stk->top];
}

bool isEmpty(Stack* stk)
{
    
    
	assert(stk);
	return stk->top == -1;
}

void CheckCapacity(Stack* stk)
{
    
    
	assert(stk);
	
	if (stk->top == stk->capacity - 1)
	{
    
    
		//扩容
		DataType* tmp = (DataType*)realloc(stk->arr, sizeof(DataType) * stk->capacity * INCREMENT);
		if (!tmp)
		{
    
    
			printf("realloc fail\n");
			exit(-1);
		}
		stk->arr = tmp;
		stk->capacity *= INCREMENT;
	}
}


二、基本思路

  1. 依次将需要单趟排序的区间入栈。
  2. 取出栈内的区间,进行单趟排序,得出key。
  3. 再将需要单趟排序的区间入栈。

当栈为空排序完毕。

在这里插入图片描述


代码示例

void QuickSortNonR(int* arr, int left, int right)
{
    
    
	Stack stk;

	StackInit(&stk, 10);

	StackPush(&stk, right);
	StackPush(&stk, left);

	while (!isEmpty(&stk))
	{
    
    
		int begin = StackTop(&stk);
		StackPop(&stk);
		int end = StackTop(&stk);
		StackPop(&stk);

		int keyi = PartSort1(arr, begin, end);
		
		//少于2个元素不需要入栈。
		if (keyi + 1 < end)
		{
    
    
			StackPush(&stk, end);
			StackPush(&stk, keyi + 1);
		}
		//少于2个元素不需要入栈。
		if (keyi - 1 > begin)
		{
    
    
			StackPush(&stk, keyi - 1);
			StackPush(&stk, begin);
		}
	}

	StackDestroy(&stk);
}

Guess you like

Origin blog.csdn.net/juggte/article/details/120420890