Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created December 31, 2013 20:07
Show Gist options
  • Save jack-wong-build/8201622 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8201622 to your computer and use it in GitHub Desktop.
A binary search function on a sorted array of strings which is interspersed with empty strings.
var findLocInInterspersedSortedArr = function(strArr, target, first, last){
var mid = Math.floor( last - first / 2);
if (strArr[mid] === ''){
var left = mid - 1;
var right = mid + 1;
while (true){
if (left < first && right > last){
return -1;
} else if (right <= last && strArr[right] !== ''){
mid = right;
break;
} else if (left >= first && strArr[left] !== ''){
mid = left;
break;
} else {
left--;
right++;
}
}
}
if (strArr[mid] === target){
return mid;
} else if (target < strArr[mid]) {
return findLocInInterspersedSortedArr(strArr, target, first, mid-1);
} else {
return findLocInInterspersedSortedArr(strArr, target, mid+1, last);
}
}
// var strArr = ["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""];
// var result = findLocInInterspersedSortedArr(strArr, "dad", 0, strArr.length-1);
// console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment