How to implement binary search algorithm in TypeScript

2 Answers

0 votes
function binarySearch(array: number[], element: number, low: number, high: number): number {
    while (low <= high) {
          let mid = low + Math.trunc((high - low) / 2);
 
          if (array[mid] == element)
              return mid;
  
          if (array[mid] < element)
              low = mid + 1;
          else
              high = mid - 1;
    }  
      
    return -1;
}
 
const array = [3, 4, 6, 8, 9, 10, 12, 20, 27, 30, 31];
const number_to_find = 10;
  
const index = binarySearch(array, number_to_find, 0, array.length);
          
if (index == -1) {
    console.log("Not found");
}
else {
    console.log("Found at index: " + index);
}
  
  
  
/*
run:
  
"Found at index: 5"
  
*/

 



answered Jan 18, 2022 by avibootz
edited Mar 23, 2025 by avibootz
0 votes
function binarySearch(arr: number[], toFind: number): number {
    let left: number = 0;
    let right: number = arr.length - 1;
    let mid: number = 0;
 
    while (left <= right) {
        mid = Math.ceil(left + (right - left) / 2);
 
        if (arr[mid] === toFind) {
            return mid;
        }
 
        if (arr[mid] < toFind) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
 
    return -1; // Element not found
}
 
const arr: number[] = [2, 3, 6, 7, 12, 13, 14, 17, 19, 21, 85];
const toFind: number = 13;
 
const i: number = binarySearch(arr, toFind);
 
i === -1
    ? console.log("Not found")
    : console.log("Found at index: " + i);
 
   
         
/*
run:
         
"Found at index: 5"
         
*/

 



answered Mar 23, 2025 by avibootz

Related questions

1 answer 106 views
1 answer 87 views
1 answer 102 views
1 answer 98 views
1 answer 82 views
1 answer 154 views
3 answers 250 views
...