Home > Enterprise >  Which of the following is a more efficient approach to find the second largest integer in an array?
Which of the following is a more efficient approach to find the second largest integer in an array?

Time:02-02

I am currently going through a JS BootCamp and after learning about some built-in functions in JS, I was wondering which one of the following codes is efficient.

const numbers = [5, 20, 11, 45, 24];

let max = numbers.indexOf(Math.max(...numbers));

numbers.splice(max, 1);

console.log(Math.max(...numbers));

OR

const arr = [12, 35, 1, 10, 34, 1]
    let first = -1 , second = -1;

    for(let i = 0; i <= arr.length-1; i  ){
        if(arr[i] > first){
            second = first;
            first = arr[i];
        }
        else if( arr[i] > second && arr[i] != first){
            second = arr[i];
        }
    }
    console.log(second);

CodePudding user response:

If you do big-O analysis of both algorithms, both run in linear time (O(n)). So there shouldn't be much difference between the two. However the second one would be slightly faster since it traverses the array only once.

  • Related