Home  >  Article  >  Web Front-end  >  How to find the maximum and minimum value in an array

How to find the maximum and minimum value in an array

一个新手
一个新手Original
2017-09-08 13:53:312581browse


function searchMaxMin(a,N){
        var i,max,min,tmax,tmin;        
        if(N%2==0){            
        max=(a[0]>a[1])?a[0]:a[1];            
        min=(a[0]<a[1])?a[0]:a[1];
        }        
        else
        max=min=a[0];        
        for(i=1;i<N/2;i++){            
        if(a[2*i-1]>a[2*i]){
                tmax=a[2*i-1];
                tmin=a[2*i];
                }            
                else{
                tmax=a[2*i];
                 tmin=a[2*i-1];
                }            
                if(tmax > max)                
                max = tmax;            
                if(tmin < min)                
                min = tmin;

        }
    }

Get the maximum value:

function searchMax(a,N){
        var i,max,tmax;        
        if(N%2==0){            
        max=(a[0]>a[1])?a[0]:a[1];
        }        
        else
        max=a[0];        
        for(i=1;i<N/2;i++){            
        if(a[2*i-1]>a[2*i]){
                tmax=a[2*i-1];
                }            
                else{
                tmax=a[2*i];
                }            
                if(tmax > max)                
                max = tmax;
        }        
        return max;
    }
    var data=[12,23,1,23,345,32,0]
    var dataMax=Search_max_and_min(data, data.length);
    console.log(dataMax);//345

Get the minimum value:

function searchMin(a,N){
        var i,min,tmin;        
        if(N%2==0){            
        min=(a[0]<a[1])?a[0]:a[1];
        }        
        else
        min=a[0];        
        for(i=1;i<N/2;i++){            
        if(a[2*i-1]>a[2*i]){
                tmin=a[2*i];
                }            
                else{
                 tmin=a[2*i-1];
                }            
                if(tmin < min)                
                min = tmin;

        }        
        return min;
    }
    var data=[12,23,1,23,345,32,0]
    var dataMin=Search_max_and_min(data, data.length);    console.log(dataMin);//0

The above is the detailed content of How to find the maximum and minimum value in an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn