Last active
August 12, 2019 07:45
-
-
Save YannMjl/add2573bbc77575ed728e551a26175d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Binary Search(Iterative Approach) | |
| var binarySearch = function (array, number) { | |
| var start = 0; | |
| var end = array.length - 1; | |
| // Iterate while start not meets end | |
| while (start <= end) { | |
| // Find the mid index | |
| var mid = Math.floor((start + end) / 2); | |
| // If element is present at mid, return True | |
| if (array[mid] === number) return true; | |
| // Else look in left or right half accordingly | |
| else if (array[mid] < number) | |
| start = mid + 1; | |
| else | |
| end = mid - 1; | |
| } | |
| return false; | |
| }; | |
| function findNumber(array, number) { | |
| if (binarySearch(array, number, 0, array.length-1)) { | |
| return('Number 5 exist in the array'); | |
| } else { | |
| return('Number 5 not found!'); | |
| } | |
| } | |
| var numberArray = [1, 3, 4, 2, 5, 7, 6, 8, 9]; | |
| var searched_number = 5; | |
| // will display Number 5 exist in the array | |
| console.log(findNumber(numberArray, searched_number)); | |
| // ********************************************************************************** | |
| // - In this case the run time of this script is: O(logn) | |
| // - this is a script that implement binary search through iterative approach. | |
| // - we use a while loop, which runs until it hits the base condition | |
| // - i.e start becomes greater than end. | |
| // - best case scenario is when the element we are looking for is stored in the | |
| // - middle of the array.(which means the script will only run one time) | |
| // - Worst case scenario is when the element we are looking for is stored either | |
| // - at the end or begining of the array | |
| // ********************************************************************************** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment