Algorithm design 5th assignment

题目如下:
Problem 1: DC for selecting the k-th smallest
For the given algorithm below 1 for selecting the k-th smallest from array, prove that
its average time complexity is Θ(n)
1 template T;
2 T QuickSelect (T a [ ] , int left , int right , int k )
3 {
4 if (right < left)
return a [left] ;
5 m=partition ( a , left , right ) ;
6 i f (m−left==k−1) return a [m] ;
7 else if (m−left >= k )
8 return QuickSelect (A, left , m ‒ 1 , k ) ;
9 else return QuickSelect (A,m+1,right , k ‒ (m+1 ‒ left ) ) ;
10 }
证明该算法的时间复杂度为Θ(n)
partion函数应该是二分
Then the first step is to find the middle element in a[] (using a quick sort), now those smaller than m are on the left, and those larger than m are on the right. If m-left = k-1, then a[m] is the kth largest element. If m-left>=k, then the kth largest element will be in the array to the left of m, then recursively call (A,left,m-1,k); otherwise, the kth largest element will be in the right of m In the array, and it is the k-(m+1-left) largest element, at this time, the right side can be called recursively.
It can be seen that this function is a recursive function. The key to analyzing the time complexity lies in the partition function
int partition(a,left,right){
j=left,i= a[j],x=right; // Θ(1)
while (j < x){
while(j < x && a[x]>i)
x–;
if(j < x ) swap(i,a[x])
while(j < x &&a[j] < i)
j++ ;
if(j < x)swap(i,a[j]);
}
This function has a complexity of Θ(n)
T(n) = T(n/2) + cn
= T(n/4) + (1 +1/2)cn

= T(1) + (2-1/n)cn
so T(n) = Θ(n)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729635&siteId=291194637