Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University.

Similar presentations


Presentation on theme: "Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University."— Presentation transcript:

1 Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University

2 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

3 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

4 4 Iterative Function for Binary Search Iterative function A better way to compute mid  Proportionally

5 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

6 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


Download ppt "Binary Search Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University."

Similar presentations


Ads by Google