Binary Search

November 27, 2021

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write the algorithm with O(log n) runtime complexity.

Link LeetCode Link

This is my implementation in javascript it really is a simple binary search function. The reason that it gets a faster run time than most submissions is because, during the edge cases

alt text

var search = function(nums, target) { let currPos = parseInt(nums.length/3); let maxPos = nums.length; let minPos = 0; if(target >= nums[0] && target <= nums[nums.length-1]){ while(nums[currPos] != target){ if(nums[currPos] < target){ if(currPos == maxPos-1){ if((nums[currPos] != target) && (nums[maxPos-1] != target)){ return -1; } else if(nums[currPos] == target){ return currPos; } else if((nums[maxPos-1] == target)){ return maxPos; } } minPos = currPos; currPos = parseInt((minPos + maxPos)/2); } else if(nums[currPos] > target){ if(currPos == minPos+1){ if((nums[currPos] != target) && (nums[minPos] != target)){ return -1; } else if(nums[currPos] == target){ return currPos; } else if((nums[minPos] == target)){ return minPos; } } maxPos = currPos; currPos = parseInt((minPos + maxPos)/2); } } if(nums[currPos] == target){ return currPos; } } else{ return -1; } };