-2

I have a sorted array, the first value is always equal or grater than 1, and I need to find the index of the element most to the left, which is equal or greater than N.

[1, 3, 3, 4, 5, 7, 11, 11, 12, 15]

What I need is a recursive binary search function that finds the expected element, so in the example, when N is equal to 11, it returns 6 as an output.

smunteanu
  • 422
  • 3
  • 9

2 Answers2

1

EDITED!!!

Ok, now I got the question asked, my previous response was because of not reading well the question. The answer is not much complex than previous. Note: If there's no value >= n, index will be -1, otherwise you'll get the index of the first met value in your sorted array >= n.

var n = 11;
var idx = [1, 3, 3, 4, 5, 7, 11, 11, 12, 15].findIndex(each => each >= n);
console.log('idx = '+idx);
Reflective
  • 3,854
  • 1
  • 13
  • 25
0

A simple for loop will do the trick, as seen with how it is implemented in this function.

let arr=[1, 3, 3, 4, 5, 7, 11, 11, 12, 15]; // Array you want to test
let n=11; // Number to be n
function getVal(a,num){
   for(let i=0;i<a.length;++i){
      if(a[i]>=num)return i; // Look for val that's >= n.
   }
}
getVal(arr,n);
      
Plantera
  • 36
  • 8