Created
May 21, 2017 16:10
-
-
Save SeptiyanAndika/e2f7b6722abb71d282aeb1a48f614e17 to your computer and use it in GitHub Desktop.
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
| function min(values){ | |
| return values[0]; | |
| } | |
| function max(values){ | |
| return values[values.length-1] | |
| } | |
| function mid(values){ | |
| let mid = Math.round(values.length/2); | |
| return [values[mid],mid] | |
| } | |
| function cutLeft(values,mid){ | |
| return values.slice(0, mid); | |
| } | |
| function cutRight(values,mid){ | |
| return values.slice(mid-1, values.length); | |
| } | |
| function searchBST(values,n,index,type){ | |
| if(!type){ | |
| type = ""; | |
| } | |
| if(min(values)<=n && n<=max(values)){ | |
| let midvalarr = mid(values); | |
| let midval = midvalarr[0]; | |
| let midindex = midvalarr[1]; | |
| if(type=="right"){ | |
| index += midindex; | |
| }else if(type=="left"){ | |
| index = midindex; | |
| } | |
| if(midval==n){ | |
| return index; | |
| }else if(midval>n){ | |
| index = midindex; | |
| values = cutLeft(values,midval); | |
| return searchBST(values,n,index,"left"); | |
| }else{ | |
| index+=midindex; | |
| values = cutRight(values,midval); | |
| return searchBST(values,n,index,"right"); | |
| } | |
| }else{ | |
| return -1; | |
| } | |
| } | |
| function bstDisctance(values, n,node1,node2) { | |
| let sorted = values.sort(); | |
| let index1 = searchBST(sorted,node1,0); | |
| let index2 = searchBST(sorted,node2,0); | |
| return Math.abs(index1-index2); | |
| } | |
| bstDisctance([5,6,3,1,2,4],5,3,6); | |
| bstDisctance([5,6,3,1,2,4],5,3,6); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment