码迷,mamicode.com
首页 > 其他好文 > 详细

The-ith-Element

时间:2014-10-02 18:28:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   ar   for   sp   div   art   c   

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

标签:blog   io   os   ar   for   sp   div   art   c   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!