Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Vowel Count With Binary Search
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