您的位置:首页 > 其它

算法练习五:求数组中第k大的数

2009-04-08 11:27 218 查看
static int FindK(IList<int> a, int k)
{
IList<int> listTemp;
int start=0;
int end = a.Count-1;
int middle = (start + end) / 2;
//int a=
//listTemp.a
int position = -1;

int count = 1;
while (position != k)
{
if (position < k&& position!=-1)
{
k = k - position-1;
//if (count % 2 == 0)
//{
// k--;
//}
//count++;

}
listTemp = new List<int>();
listTemp.Add(a[middle]);
position = 0;
for (int i = start; i <= end; i++)
{
if (i != middle)
{
if (a[i] <= a[middle])
{
listTemp.Insert(position,a[i]);
position++;
}
else
{
listTemp.Add(a[i]);
}
}
}

a = listTemp;
if (listTemp.Count == 1)
return a[position];
if (position < k)
{
//if (position + 1 == k)
//{
// return a[position];
//}
start = position +1;
//a = listTemp;
end = listTemp.Count-1;
middle = (start + end) / 2;
}
if (position >k)
{
start = 0;
end = position-1 ;

middle = (start + end) / 2;

}
}

return a[position];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: