Skip to content

Instantly share code, notes, and snippets.

@jesslilly
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesslilly/8870059 to your computer and use it in GitHub Desktop.
Save jesslilly/8870059 to your computer and use it in GitHub Desktop.
Search a sorted array in js. O(log n)
#!/usr/bin/env node
var util = require("util");
util.puts("Search Array for value N.");
// This only took me 12 minutes to do on a white board.
// This has a complexity of O(log n).
// 0 1 2 3 4 5 6 7 8 9 10 11
var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16 ];
var _indexOf = function(pos1, pos2, n) {
var middle = pos2 - Math.round((pos2 - pos1) / 2);
if (n === a[middle]) {
return middle;
} else if (n > a[middle]) {
return _indexOf(middle, pos2, n);
} else if (n < a[middle]) {
return _indexOf(pos1, middle, n);
}
};
var indexOf = function(a, n) {
return _indexOf(0, a.length, n);
};
util.puts("In array a, indexOf 1 is " + indexOf(a, 1));
util.puts("In array a, indexOf 2 is " + indexOf(a, 2));
util.puts("In array a, indexOf 12 is " + indexOf(a, 12));
util.puts("In array a, indexOf 16 is " + indexOf(a, 16));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment