Skip to content

Instantly share code, notes, and snippets.

@alexhawkins
Last active September 4, 2016 09:46
Show Gist options
  • Save alexhawkins/4b0490a7db0338502836 to your computer and use it in GitHub Desktop.
Save alexhawkins/4b0490a7db0338502836 to your computer and use it in GitHub Desktop.
Binary Search Algorithms with Shuffle and Range
/*
#DATA STRUCTURES & ALGORITHMS
A) Binary Search with RANGE and Shuffle algorithms:
-Algorithmic Steps
1) If needle == value in haystack, we're done. Exit.
2) If needle < middle value in haystack, go left. Go to step 1.
3) If needle > middle value in haystack, go right. Go to step 1.
*/
var binarySearch = function(haystack, needle) {
//make sure haystack is sorted;
haystack = haystack.sort(function(x, y) {
return x - y;
});
var lowIndex = 0,
highIndex = haystack.length - 1,
middle;
while (lowIndex <= highIndex) {
//adjust new middle point either left or right
middle = Math.floor((highIndex + lowIndex) / 2);
if (needle === haystack[middle])
return console.log('"' + needle + '"' + ' found at index: ' + middle);
//adjust search area to the right
else if (needle > haystack[middle])
lowIndex = middle + 1;
//adjust search area to the left
else
highIndex = middle - 1;
}
//otherwise not found
return console.log('"' + needle + '"' + ' not found!');
};
//CREATE A LARGE ARRAY USING OUR
//METHOD 1: var haystack = Array.apply(null, Array(1000)).map(function(_, index) { return index});
//METHOD 2;
var range = function(start, stop, step) {
var arr = [];
while (start <= stop) {
arr.push(start);
start += step;
}
return arr;
};
//use Fisher Yates shuffle to shuffle our array
Array.prototype.shuffle = function() {
var listClone = this.slice(), //clone list
rndPos, temp;
for (var i = 0; i < listClone.length; i++) {
rndPos = Math.floor(Math.random() * listClone.length);
temp = listClone[i]; //store i value in temp array;
listClone[i] = listClone[rndPos]; //replace i with random value
listClone[rndPos] = temp; // replace random with origina i stored in temp;
}
return listClone;
};
//TESTS
//var haystack = ['a' , 'b' , 'c' , 'd', 'e' , 'f' , 'k']
var haystack = range(0, 1000, 3).shuffle();
binarySearch(haystack, 3); //"3" found at index: 1
binarySearch(haystack, 333); // "333" found at index: 111
haystack = range(0, 1000, 5).shuffle();
console.log(haystack);
binarySearch(haystack, 786); //"786" not found!
binarySearch(haystack, 785); //"785" found at index: 157
haystack = [];
binarySearch(haystack, 973465); //"973465" not found!
binarySearch(haystack, null); //"null" not found!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment