Created
December 31, 2013 20:07
-
-
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.
This file contains 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 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