Last active
August 29, 2015 13:56
-
-
Save jesslilly/8870059 to your computer and use it in GitHub Desktop.
Search a sorted array in js. O(log n)
This file contains hidden or 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
#!/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