求数组中最大元素值的3种方法对比

给一个序列,求其最大值。很简单的一道题对不对?思路一共有三种:

  • 暴力求解
  • 递归
  • 建最大堆
#include <iostream>
#include <algorithm>
#include <vector>
#include <time.h>
#include <stdlib.h>
using namespace std;


int findmax(vector<int> &arr, int l, int r){
	int m = (l+r)/2;
	int u, v, x;
	if(l == r-1){
		return max(arr[l],arr[r]);
	}else{
		 u=findmax(arr, l, m);
		 v=findmax(arr, m, r);
		 x = max(u,v);
		 return x;
	}
}

int findMax(vector<int> &arr)
{
    int res = 0x80000000;

    for(unsigned i = 0; i < arr.size(); ++i)
    {
        res = max(res,arr[i]);
    }
    return res;
}

void heapify(vector<int> &a, int idx)
{
    int ll = idx*2+1;
    int rr = 2*(idx+1);
    int largest_idx = idx;

    if(ll < a.size() && a[ll] > a[largest_idx])
        largest_idx = ll;
    if(rr < a.size() && a[rr] > a[largest_idx])
        largest_idx = rr;

    if(largest_idx != idx)
    {
        int t = a[idx];
        a[idx] = a[largest_idx];
        a[largest_idx] = t;
        heapify(a,largest_idx);
    }
}

int buildMaxHeap(vector<int> &a)
{
    for(int j = a.size()/2; j >= 0; --j)
    {
        heapify(a,j);
    }
    return a[0];
}

int main()
{
    int y = 1;
    while(1)
    {
        cout<<"输入元素个数:";
        cin>>y;
        if(y < 1)
        {
            break;
        }

        srand(time(NULL));
        cout<<"正在赋值。。。"<<endl;
        vector<int> a(y);
        for(unsigned i = 0; i < y; ++i)
        {
            a[i] = rand()%(y*10);
        }
        cout<<"创建数组完成。。。"<<endl;

        cout<<endl<<"递归求解开始。。。"<<endl;
        clock_t begTime = clock();
        cout<<findmax(a,0,y-1)<<endl;
        clock_t endTime = clock();
        cout<<"耗时:"<<endTime-begTime<<endl;

        cout<<endl<<"循环求解开始。。。"<<endl;
        begTime = clock();
        cout<<findMax(a)<<endl;
        endTime = clock();
        cout<<"耗时:"<<endTime-begTime<<endl;

        cout<<endl<<"堆求解开始。。。"<<endl;
        begTime = clock();
        cout<<buildMaxHeap(a)<<endl;
        endTime = clock();
        cout<<"耗时:"<<endTime-begTime<<endl;
    }
    return 0;
}

暴力求解的耗时最少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值