Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: ec2620m.htm Office: Tel 3049.

Similar presentations


Presentation on theme: "ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: ec2620m.htm Office: Tel 3049."— Presentation transcript:

1 ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: http://people.math.yorku.ca/~zyang/it ec2620m.htm Office: Tel 3049

2 Searching

3 3 Key Points of this Lecture Searching arrays –Linear search –Binary search –Best, average, and worst cases

4 4 Searching in General “A query for the existence and location of an element in a set of distinct elements” Elements have searchable keys associated with a stored record –search on keys – e.g. name –to find an element – e.g. phone number Two goals of searching –existence  does the person exist? –location  where are they in the phone book? Isolate searching for “keys” – all keys have the same data type

5 5 Definition Suppose k 1, k 2, …, k n are distinct keys, and that we have a collection T of n records of the form (k 1, I 1 ), (k 2, I 2 ), …, (k n, I n ), where I j is information associated with key k j. Given a particular key value K, the search problem is to locate the record (k j, I j ) in T such that k j = K. Exact-match query Range query

6 6 Review of Array Algorithms Write a static method that determines the range (the difference between the largest and smallest element) for a fully populated array of ints. How is the above example similar to searching? –find the largest/smallest value in a set of elements Searching  find a given value in a set of elements

7 7 Searching Arrays Write a static method that determines the location (the array index) for a given value in a fully populated array of ints, return “–1” if the value is not in the array Example

8 8 Binary Search Make your first guess in the middle of the range If not the target element, determine which sub-range you have to search Make your next guess in the middle of this sub-range Repeat Example

9 9 Best, Worst and Average What’s the best case for search? –Linear  first element  1 compare –Binary  middle element  1 compare What’s the worst case for search? –Linear  not there  n compares –Binary  not there  logn compares What’s the average case for search? –Linear  middle element  n/2 compares –Binary  50/50…  logn - 1 compares

10 10 What’s the difference? Toronto phone book  2 million names –Avg. Linear  1 million compares –Avg. Binary  20 compares For 2 million records, binary search is 50,000 times faster on average What’s the cost –To do binary search, we need a sorted array –Sorting…next lecture!


Download ppt "ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: ec2620m.htm Office: Tel 3049."

Similar presentations


Ads by Google