Home > Article > Web Front-end > js binary search recursion and while writing code sharing
This article mainly shares with you the js binary search recursion and while writing code, hoping to help everyone.
1. Recursion
Mainly controls three variables: start end mid, start end mid, repeat it and it will be ok.
const data = [18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]function Recursive(s,data){ let len = data.length let start = 0 let end = len-1 let mid return find(start,end,s)}function find(start,end,s){ mid =Math.ceil((end+start)/2) if (s==data[mid]) { return s } else if(s>data[mid] && start <= end) { end = mid-1 return find(start,end,s) } else if(s<data[mid] && start <= end){ start = mid+1 return find(start,end,s) } else{ return null } } let v = f(15,data) console.log("vvvv",v)
while loop
const data = [18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]function while_find(s){ let len = data.length let start = 0 let end = len-1 let mid while(start <= end){ mid =Math.ceil((end+start)/2) if (s<data[mid]) { start = mid+1 } else if(s>data[mid]){ end = mid-1 } else{ return s } } return null} let v= while_find(8) console.log("vvvv",v)
Mainly draws on this article. Click to open it. There are also some variations of the binary algorithm. Interested students can Go check it out Great writing.
Related recommendations:
php binary search algorithm example sharing
php binary search example code for recursive and non-recursive implementations
js basic algorithm: bubble sort, binary search
The above is the detailed content of js binary search recursion and while writing code sharing. For more information, please follow other related articles on the PHP Chinese website!