非递归快速排序php,快排序的非递归实现(原创)
本文簡(jiǎn)要介紹快排序的非遞歸實(shí)現(xiàn)方式并給出了C語言版本的源代碼,非遞歸實(shí)現(xiàn)由于沒有函數(shù)調(diào)用的消耗,相對(duì)于遞歸方式有一定的優(yōu)勢(shì)。
在快排序的遞歸實(shí)現(xiàn)中,函數(shù)quicksort(int nlow, int nhigh)遞歸的時(shí)候兩個(gè)參和high在改變。
非遞歸實(shí)現(xiàn)中可以用兩個(gè)棧int low[MAX_SIZE] , int high[MAX_SIZE]來模擬系統(tǒng)棧對(duì)nlow和nhigh的
存儲(chǔ)情況。非遞歸快排的具體實(shí)現(xiàn)比較簡(jiǎn)單,需要說明的是,MAX_SIZE這里等于32就可以了,因?yàn)?/p>
快速排序的空間復(fù)雜度是O(log2N),而整數(shù)最大時(shí)2^32,因此兩個(gè)模擬棧的大小是32就可以了。
非遞歸快排序的源碼如下:
/*
* Author: puresky
* Date: 2010/01/08
* Purpose: Nonrecursive quicksort
*/
#include
#include
#include
//Nonrecursive quicksort
void quicksort2(int a[], int n)
{
#define STACK_MAX 32 //the space complexity of quicksort is O(logN), so 32 is enough!
#define SWAP(a, b) {int temp = a; a = b; b = temp;}
int low[STACK_MAX]; //low position stack
int high[STACK_MAX]; // high position stack
int top = -1; //stack top
top++;
low[top] = 0;
high[top] = n - 1;
while(top >= 0) // stack is not empty
{
int L = low[top];
int R = high[top];
top--;
//printf("TOP:%d,L:%d,R:%d\n", top, L, R);
if( L < R)
{
//partion
SWAP(a[L], a[L + rand() % ( R - L + 1)]);
int i;
int m = L;
for(i = L + 1; i <= R; ++i)
{
if(a[i] < a[L])
{
++m;
SWAP(a[m], a[i]);
}
}
SWAP(a[m], a[L]);
//left part entering stack
if(L < m - 1)
{
top++;
low[top] = L;
high[top] = m - 1;
}
//rigth part entering stack
if(m + 1 < R)
{
top++;
low[top] = m + 1;
high[top] = R;
}
}
}
}
void print(int a[], int n)
{
int i;
for(i = 0; i < n; ++i)
printf("%d ", a[i]);
printf("\n");
}
int* init_array(int n)
{
int i;
int *a = (int*)malloc(sizeof(int) * n);
for(i = 0; i < n; ++i)
a[i] = rand() % n;
return a;
}
void free_array(int *a)
{
free(a);
}
int main(int argc, char** argv)
{
srand(time(NULL));
const int n = 100;
int *a = init_array(n);
quicksort2(a, n);
print(a, n);
free_array(a);
system("pause");
return 0;
}
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的非递归快速排序php,快排序的非递归实现(原创)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle sql文本 参数,ORAC
- 下一篇: ubuntu版php开发工具,Ubunt