Home > Web Front-end > JS Tutorial > body text

How to find the maximum and minimum value in an array

一个新手
Release: 2017-09-08 13:53:31
Original
2538 people have browsed it


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;

        }
    }
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!