JavaScript Recursion finding the smallest number?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following is our array −

var numbers=[10,101,76,56,5,210,3,100];

To find the smallest number, the code is as follows −

Example

function findMinimumElementUsingRecursive(numbers) {
   if (numbers.length==1){
      return numbers[0];
   }
   else if(numbers[0]>numbers[1]) {
      return findMinimumElementUsingRecursive(numbers.slice(1));
   } else {
      return
      findMinimumElementUsingRecursive([numbers[0]].concat(numbers.slice(2)));
   }
}
var numbers=[10,101,76,56,5,210,3,100];
console.log("The minimum element
is="+findMinimumElementUsingRecursive(numbers));

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo152.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo152.js
The minimum element is=3
raja
Published on 11-Sep-2020 08:39:24
Advertisements