Created
November 20, 2015 06:28
-
-
Save calderonroberto/0ddb2f4d8fb84b97bd44 to your computer and use it in GitHub Desktop.
Vowel Count With Binary Search
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
var withBinarySearch = function (s) { | |
var vowels = 0; | |
var vowelArray = ["a","e","i","o","u"]; //already sorted | |
for (var i = 0; i < s.length-1; i++){ | |
var search = binarySearch(vowelArray,s[i].toLowerCase(),0,4); | |
if ( search !== -1 ){ | |
vowels++; | |
} | |
} | |
return vowels; | |
}; | |
/* | |
* Utility function | |
*/ | |
function binarySearch (a,value,lo,hi) { | |
if (lo>hi) { | |
return -1; | |
} | |
var mid = Math.round((lo+hi)/2); | |
if (value < a[mid]) { | |
return binarySearch(a,value,lo,mid-1); | |
} | |
else if (value > a[mid]) { | |
return binarySearch(a,value,mid+1,hi); | |
} | |
else if (value === a[mid]) { | |
return mid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment