Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict'
- const binarySearch = (arr, value) => {
- let begin = 0;
- let end = arr.length - 1;
- let middle = parseInt(end / 2);
- let index = -1;
- while (begin <= end) {
- if (arr[middle] === value) {
- index = middle;
- break;
- } else {
- if (arr[middle] > value) {
- end = middle - 1;
- } else {
- begin = middle + 1;
- }
- middle = parseInt((begin + end) / 2);
- }
- }
- return index;
- }
- console.log('Looking for 6: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 6));
- console.log('Looking for 34: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 34));
- console.log('Looking for 1: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 1));
- console.log('Looking for 30: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 30));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement