首页 > 其他 > 详细

The-ith-Element

时间:2014-10-02 17:26:33      阅读:306      评论:0      收藏:0      [点我收藏+]

Brief: the-ith-element,given a array A with n element , return the i-th element of A.  A(n,i)

this problem can be solved using quick-sort idear, every time we choose a pivot ,after rearrangement, we know the pivot is the i-th element of A, so we can fixed this problem as the follow action.

i) choose  pivot, rearrangement array, get the pivot index of j;

ii) if j > i , then recursion the 1-th partition , A(1-th , i);

iii)if j < i, then recursion the 2-th partition, A(2-th, i-j);

 

 

int element(int *array, int left, int right, int index)
{
	if(left >= right)
		return array[left];
	int pivot = array[left];
	int i=0, j = 0;

	for(i=left+1,j = left+1; j <=right; ++j)
	{
		if(array[j] < pivot)
			swap(array[i++], array[j]);
	}
	swap(array[left], array[i-1]);

	//pivot is the (i-left)-th element, and pivot‘s index is i-1

	if(index == i-left)
		return array[i-1];
	else if(index < i-left)
		return element(array, left, i-2, index);
	else
		return element(array, i,right, index-i+left);
}

  

The-ith-Element

原文:http://www.cnblogs.com/memoryh/p/4004231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!