binary search jyh-shing roger jang ( 張智星 ) csie dept, national taiwan university

Post on 13-Dec-2015

213 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Binary Search

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

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

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

Iterative Function for Binary Search

Iterative function

A better way to compute mid Proportionally

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

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

top related