演算法導論 改進快排(3) 棧深度 習題7 4

2021-07-02 15:28:33 字數 664 閱讀 5567

問題:快排演算法包含了兩個對自身的遞迴呼叫,每次遞迴呼叫的資訊存入棧中,作業系統給程式的棧空間是有限的,如果陣列很大,則很容易造成棧溢位,這樣程式就崩潰了。

思路:quicksort中的第二個遞迴用乙個迴圈控制結構來代替----尾遞迴

**實現:

#include#include#includeusing namespace std;

//交換兩個數

void swap(int & a, int &b)

//int t_partition(int *a, int p, int r)

} swap(a[i+1],a[r]);

return i+1;

}void tail_quicksort(int *a, int p, int r)

int tailfactorial(int n, int result)

我們從上面的程式可以看出,我們以計算5的階乘為例進行說明:

factorial(5) }}}

}}}}}}}}}

120tailfactorial(5, 1)

tailfactorial(4, 5)

tailfactorial(3, 20)

tailfactorial(2, 60)

tailfactorial(1, 120)

120

演算法導論之快排

快速排序法原理也是用了分治法,主要原理是將陣列a分為a p.q 1 和a q 1.r 然後調整元素使得a p.q 1 小於等於a q a q 小於等於a q 1.r 然後不斷的遞迴,到最後就排序完成。p i是小於等於x的,i 1 j 1是大於等於x的,j r是還未處理的 i每次從list前面往後走 ...

演算法導論習題7 4 快排中堆疊深度的優化

quick sort time complexity is nlgn the way is find an element,and partition the array according to this element includeusing namespace std int partiti...

第k個小的數 bfprt演算法與快排改進

public static intfindk int nums,int m,int n int k while i temp if i nums m nums j nums j temp if j 1 k else if j 1 k else public static void main stri...