您的位置:首页 > 其它

分治法找出数组中第二大数

2014-11-19 16:50 344 查看
#include <span style="font-family: Arial, Helvetica, sans-serif;"><iostream></span>
using namespace std;

class Res
{
public:
int max;
int secmax;
};

Res maxnum(int *a,int first,int last)
{
int mid;
Res res;
if (last-first==1)
{
if (a[first] > a[last])
{
res.max = a[first];
res.secmax = a[last];
}
else
{
res.max = a[last];
res.secmax = a[first];
}
return res;
}

if (last == first)
{
return res;
}

else
{
mid = (first+last)>>1;
if (maxnum(a, first, mid).max > maxnum(a, mid, last).max)
{
res.max =maxnum(a, first, mid).max;
res.secmax = maxnum(a, mid, last).max;
}
else
{
res.max = maxnum(a, mid, last).max;
res.secmax = maxnum(a, first, mid).max;
}

return res;
}
}

int main(int argc , const char * argv[])
{
int a[10] ={1,2,3,9,5,6,7,8,4,0};
cout< return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: