算法练习五:求数组中第k大的数
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];
}
posted on 2009-04-08 11:27 Love Fendi 阅读(751) 评论(1) 编辑 收藏 举报