Last active
August 29, 2015 14:26
-
-
Save ikrabbe/7bd566eecaa4fca96d03 to your computer and use it in GitHub Desktop.
Three Javascript Functions to manage sorted arrays through a binary search function
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
/* Search in a sorted array A with the comparison function gt(v,w), that | |
* returns true if v greater than w and false otherwise, for a value x. | |
* Returns index i with 0 <= i < A.length, if the element has an exact match. | |
* Otherwise it returns the position p<0, that we can insert the new value | |
* sorted behind position -p-1 | |
*/ | |
function searchArray(A,x,gt) | |
{ | |
var l=A.length; | |
var low=0,high=l-1,mid=0; | |
var r=true; | |
if (l==1) { | |
if (!gt(A[0],x) && !gt(x,A[0])) return 0; | |
} | |
else r=true; | |
while (low<=high) { | |
mid=(((high-low)/2)>>0)+low; | |
if (r=gt(A[mid],x)) high=mid-1; | |
else if (gt(x,A[mid])) low=mid+1; | |
else return mid; | |
} | |
return -(mid+(r?1:2)); | |
} | |
/* insertSortedArray inserts value x into the sorted Array A with respect | |
* to the comparison function gt(v,w), that returns true when v greater than w, | |
* such that A remains sorted. It returns the position from the searchArray call. */ | |
function insertSortedArray(A,x,gt) | |
{ | |
var pos,ins; | |
pos=searchArray(A,x,gt); | |
if (pos<0) ins=-pos-1; | |
if (ins>=0) A.splice(ins,0,x); | |
return pos; | |
} | |
/* removeSortedArray removes value x from the sorted Array A, using the | |
* comparison function gt(v,w), that returns true for v greater than w and | |
* false otherwise. It returns the position from the searchArray call. */ | |
function removeSortedArray(A,x,gt) | |
{ | |
var pos; | |
pos=searchArray(A,x,gt); | |
if (pos>=0) A.splice(pos,1); | |
return pos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment