binary search jyh-shing roger jang ( 張智星 ) csie dept, national taiwan university
TRANSCRIPT
![Page 1: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/1.jpg)
Binary Search
Jyh-Shing Roger Jang (張智星 )CSIE Dept, National Taiwan University
![Page 2: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/2.jpg)
2
Binary Search Algorithm
Definition Find the position of a specified input key value within an
array sorted by key value Daily life example
翻書找頁碼從字典中找單字
Numerical example
![Page 3: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/3.jpg)
3
Recursive Function for Binary Search
Recursive function
Example usage index = binarySearch(vec, 0, vec.size()-1, value)
How to compute mid? mid=(left+right)/2 mid=left+(right-left)/2
![Page 4: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/4.jpg)
4
Iterative Function for Binary Search
Iterative function
A better way to compute mid Proportionally
![Page 5: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/5.jpg)
5
Summary
Comparisons Linear search
Complexity O(n) For any arrays Considerable speedup if frequently searched items are placed at
the beginning Binary search
Complexity O(log(n)) For sorted arrays
Hash search Complexity O(1) For arrays pre-processed by hash functions
![Page 6: Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University](https://reader035.vdocuments.mx/reader035/viewer/2022072006/56649f505503460f94c72ca3/html5/thumbnails/6.jpg)
6
Extensions
Other similar problems Interval finding
Given a sorted vector, find the interval of a given value. Non-zero element finding
Given a sorted vector, find the no. of positive elements. Insertion sort
… Preprocessing for binary search
Binary search using multiple keys Sorted arrays with multiple keys Stable sort for multiple keys starting from the least-significant key