Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var arr = [1,2,3,4,5,6,7,8,9,10]
- function binarySearch(elem, arr) {
- //loop through array and partition
- var max = arr.length - 1,
- min = 0,
- mid = arr[Math.floor(len/2)];
- if (arr.length === 0){
- return "Key not found, array is empty";
- }
- else if (elem === arr[max]){
- return max;
- }
- else if (elem === arr[min]) {
- return 0;
- }
- //perform the binary search here
- else {
- while(min < max) {
- if(elem > arr[mid]) {
- //move your min up, niqqa
- min = mid + 1;
- }
- else {
- //partition up to mid
- max = mid;
- }
- }
- if((arr[min] === elem)&&(max === min)){
- return min;
- } else {
- return "Key not found in array, you're searching for shit";
- }
- }
- }
- binarySearch(4, arr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement