Notes of Introduction to Algorithm(Order Statistics)

 

The ith order statistic of a set of n elements is the ith smallest element. For example, the minimum of a set of elements is the first order statistic (i = 1), and the maximum is the nth order statistic (i = n). The asymptotic running time of the simple problem of finding a minimum or maximum is Θ(n). Yet select the ith smallest element appears more difficult but it also only need Θ(n) time.

Here is a divide-and-conquer algorithm for the selection problem. The procedure selection is modeled after the quicksort algorithm. As in quicksort, the idea is to partition the input array recursively. But unlike quicksort, which recursively processes both sides of the partition, selection only works on one side of the partition.

// same partition procedure as in quick sort
int partition(int a[], int p, int r)
{
	int i=p,j;
	for(j=p+1;j<=r;j++)
	{
		if(a[j]<a[p])
		{
			++i;
			int temp=a[i]; a[i]=a[j]; a[j]=temp;
		}
	}
	int temp=a[i]; a[i]=a[p]; a[p]=temp;
	return i;
}
/*
 *	select the ith element from an unsorted array.
 */
int selection(int a[], int p, int r, int i)
{
	if(p==r)
		return a[p];
	int q = partition(a,p,r);
	int k = q-p+1;
	if(i==k)// checks whether a[q] is the ith smallest element
		return a[q];
	if(i<k) //the desired element lies on the low side of the partition
		return selection(a,p,q-1,i);
	else // the desired element lies on the high side of the partition
		return selection(a,q+1,r,i-k);
}

Related Entries

Comments

what if each time pivot is the worst one.. It might lead to O(n^2) run time right?

correct

Post a Comment