Dichotomy search JS algorithm

dichotomy search algorithm:
When dichotomy is used to search, data needs to be arranged in order.
The main idea is: (set the array interval to find is array[s, e]).
(1)Determine the middle position of the interval M
(2)Comparing the search value T with array [m], if the search is equal, the search returns to this location successfully; otherwise, the new search area is determined and the binary search continues.
The area is as follows:
Array is arranged from small to large.
array[m]>TFrom the order of arrays, we can see array[m,… E]> T;
Therefore, the new interval is array[s,… M-1],
Like finding the interval array[s above,… M-1].
Each search is compared with the intermediate value to determine whether the search is successful or not. If the current search interval is not successful, the search interval is reduced by half, and the lookup can be repeated.
Time complexity: O (log2n).

 

let arr = [0, 1, 2, 4, 5, 6, 7, 8]; let arr2 = [88, 77, 66, 55, 44, 33, 22, 11]; BinarySearch(arr2, 77); BinarySearch(arr, 2); function BinarySearch(arr, target) { let s = 0; let e = arr.length – 1; let m = Math.floor((s + e) / 2); let sortTag = arr[s] <= arr[e];//Determining sorting orderwhile (s < e && arr[m] !== target) { if (arr[m] > target) { sortTag && (e = m – 1); !sortTag && (s = m + 1); } else { !sortTag && (e = m – 1); sortTag && (s = m + 1); } m = Math.floor((s + e) / 2); } if (arr[m] == target) { console.log(‘Found, location%s’, m);return m; } else { console.log(‘I didn’t find it.return -1; } }

Leave a Reply

Your email address will not be published. Required fields are marked *