算法练习五:求数组中第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];
}
{
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];
}
相关文章推荐
- 算法题练习(二)------哈夫曼树,比较奇数与偶数个数,查找一个数组的第K小的数
- 面试算法:lg(k)时间查找两个排序数组合并后第k小的元素
- 算法题(一)--找出数组中第k大的数并输出其下标(数组中的数有重复)
- (算法)Partition方法求数组第k大的数
- 算法练习4.Median of Two Sorted Arrays两个有序数组的中位数(递归、分治)
- 算法练习:两指针之有序数组去重
- 2018年全国多校算法寒假训练营练习比赛(第五场) (树状数组模板)
- 2018年全国多校算法寒假训练营练习比赛(第五场) Big Water Problem(树状数组)
- 算法(三)找出数组中第K大元素
- 【算法练习】数组排序
- 求数组的第K小数,O(nlogn) 和 O(N)的算法
- 【算法练习】二叉树方法对数组进行排序
- 练习4.1-5最大子数组线性算法及证明
- 【算法】寻找数组第K大数算法总结
- 每天一道算法题目(18)——取等长有序数组的上中位数和不等长有序数组的第k小的数
- 每天一道算法题(32)——输出数组中第k小的数
- 算法思想:关于找数组中第K大的数的思考
- [经典算法题]寻找数组中第K大的数的方法总结
- 算法练习——返回一个set数组
- 每天一道算法题目(18)——取等长有序数组的上中位数和不等长有序数组的第k小的数