Created
April 7, 2016 00:21
-
-
Save Williammer/35b3c20fce838e9adfe833479c601049 to your computer and use it in GitHub Desktop.
Algorithm Search Implementations
This file contains 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
function binSearch(arr, data) { | |
var upperBound = arr.length - 1; | |
var lowerBound = 0; | |
while (lowerBound <= upperBound) { | |
var mid = Math.floor((upperBound + lowerBound) / 2); | |
if (arr[mid] < data) { | |
lowerBound = mid + 1; | |
} else if (arr[mid] > data) { | |
upperBound = mid - 1; | |
} else { | |
return mid; | |
} | |
} | |
return -1; | |
} |
This file contains 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
function rotatedArrayMinBinarySearch(arr) { | |
var len = arr.length, | |
start = 0, | |
end = len - 1, | |
mid, min; | |
// end edge: search range <= 1, no mid val in between. | |
while (Math.floor((end - start) / 2) > 0) { | |
mid = Math.floor((end - start) / 2); | |
// rotated end val flags whether the shorter streak is on upper/lower frag, which contains the rotated point. | |
if (arr[end] > arr[mid]) { | |
// min should be in lower frag | |
end = mid - 1; | |
min = arr[mid]; | |
} else if (arr[end] < arr[mid]) { | |
// min should be in lower frag | |
start = mid + 1; | |
min = arr[end]; | |
} else { | |
// can't be equal | |
return -1; | |
} | |
} | |
return min; | |
} | |
var mmm = rotatedArrayMinBinarySearch([5, 6, 7, 8, 9, 1, 2, 3, 4]); | |
document.body.innerHTML = mmm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment