Home > Software engineering >  First occurence of an element in a sorted array
First occurence of an element in a sorted array

Time:08-27

I am trying to solve a leetcode problem which requires to find first occurrence of an element. A naive approach is doing a linear search which is of O(n) complexity, a better approach is to use binary search for this using O(log n) time.

I am going with iterative approach for binary search but it gets me into an infinite loop and i am really not able to find what's the problem.

function firstOccurenceOfElement(arr, key) {
  let start = 0;
  let end = arr.length - 1;

  let firstOccurence = -1;

  while (start <= end) {
    let mid = Math.floor(start   ((end - start) / 2))
    let count = 0;
    if (arr[mid] == key) {
      firstOccurence = mid;
      end = mid - 1;

    }
    if (arr[mid] > key) {
      end = mid - 1;
    }
    if (arr[mid] < key) {
      start = mid   1;
    }
  }
  return firstOccurence;
}

let arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9];
let key = 5;
console.log(firstAndLastOccurenceOfElement(arr, key));

CodePudding user response:

Your variables are not named properly. You should check them, I have edited it to a workable solution and it works fine.

   function firstOccurenceOfElement(arr, key) {
      let start = 0;
      let end = arr.length - 1;

      let firstOccurence = -1;

      while (start <= end) {
        let mid = Math.floor(start   ((end - start) / 2))
        let count = 0;
        if (arr[mid] == key) {
          firstOccurence = mid;
          end = mid - 1;

        }
        if (arr[mid] > key) {
          end = mid - 1;
        }
        if (arr[mid] < key) {
          start = mid   1;
        }
      }
      return firstOccurence;
    }

    let arr = [2, 5, 5, 5, 6, 6, 8, 9, 9, 9];
    let key = 5;
    console.log(firstOccurenceOfElement(arr, key));
  • Related