searching cse 103 lecture 20 wednesday, october 16, 2002 prepared by doug hogan

34
Searching Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Upload: ambrose-moore

Post on 18-Jan-2018

218 views

Category:

Documents


0 download

DESCRIPTION

Announcement Regarding Homework… Some of you continue to lose points for incomplete homework headers. Set them up as follows: // Name: Your Name // Section: 6 // ID: 1111 // Purpose: This program will... // (or call it description) // Inputs: first input, second // input, etc. // Outputs: first output, etc. PLEASE use digits, not words, for section numbers to make sorting easier.

TRANSCRIPT

Page 1: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

SearchingSearchingCSE 103Lecture 20

Wednesday, October 16, 2002

prepared by Doug Hogan

Page 2: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Announcement(s)Announcement(s) Lab 7 instructions are on the web. Homework 3 due Monday.

Page 3: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Announcement Announcement Regarding Homework…Regarding Homework…

Some of you continue to lose points for incomplete homework headers. Set them up as follows:// Name: Your Name// Section: 6// ID: 1111// Purpose: This program will ...// (or call it description)// Inputs: first input, second// input, etc.// Outputs: first output, etc.

PLEASE use digits, not words, for section numbers to make sorting easier.

Page 4: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Overview of TodayOverview of Today Warm-up exercises Working up to Linear search Binary search A brief discussion on running times

Page 5: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Warm-up ExercisesWarm-up Exercises Create an array called data that holds 8

numbers of type double. double data[8];

Set the first element of this array to be 5. data[0] = 5;

Set the fifth element of this array to be -9; data[4] = -9;

Page 6: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Warm-up Exercises, ctd.Warm-up Exercises, ctd. Assume we’ve initialized all 8 elements. Write a loop that goes through data and

prints each element of the array with its index, one element per line. for(int i = 0; i < 8; i++){ cout << i << ‘\t’ << data[i] << endl;}

Page 7: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Output from Previous…Output from Previous…For one sample set of data:0 51 72 -13 34 -95 176 07 -2

Page 8: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Printing SelectivelyPrinting Selectively Suppose we wanted to print out the array again, this

time displaying just the positive values: for(int i = 0; i < 8; i++){ if(data[i] > 0) { cout << i << ‘\t’ << data[i] << endl; }}

Very important to note that we’re looking at the value STORED at i, not i itself.

Confusing i and data[i] is one of the most common errors when working with arrays.

Page 9: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Searching for a Specific Searching for a Specific ValueValue

Now suppose we want to look for a specific value that’s stored in the array. We call that value the key. Suppose it’s been declared double key = 0;

We’d like to know where it’s found (at which index).

Modify the previous code to solve this problem.

Page 10: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Search, First FormSearch, First Form Searching for key declared with

double key = 0; for(int i = 0; i < 8; i++){ if(data[i] == key) { cout << key << “ found at “ << i; }}

What could go wrong? if key is not found, nothing is displayed

Page 11: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Adding Some Error HandlingAdding Some Error Handling If the key isn’t found, an error message would

be nice. Use a boolean flag:

bool found; Start by assuming the search has failed.

(found = false;) Perform search. When the key is found, set found

to true. (found = true;) If search completes and key isn’t found, found is

still false. Print error message in this case.

Page 12: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Adding Some Error HandlingAdding Some Error Handlingbool found = false; for(int i = 0; i < 8; i++){ if(data[i] == key) { found = true; // record success cout << key << “ found at “ << i;

}}if(!found) // report failure{ cout << key << “ not found.”;}

Page 13: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Generalizing to a FunctionGeneralizing to a Function Exercise: write the function header for search

We need to send in the array to be searched how many elements are in the array the search key

The function will give back the location where the key was found

or -1 if the key was not found Answer:int Search(double array[], int size, double key)

Remember that passing an array as a parameter requires empty brackets

Page 14: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

More on Parameter PassingMore on Parameter Passing int Search(double array[], int size,

double key) Recall that arrays are passed by reference by default,

not passed by value, by default. That means the search method could change the array. Since we don’t want to change the array, it’s a good

idea to pass by constant reference: int Search(const double array[], int size, double key)

Page 15: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Adding the CodeAdding the Code We’ve named the parameter “array,” so we’ll need to

change the hardcoded name “data” to “array.” We want to use the size we pass in instead of

hardcoding the size as 8. We no longer want to print the index; we want to

return it. return i instead of displaying in the loop return -1 in the error condition

Why -1? It could never be the array subscript

Page 16: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Search FunctionSearch Functionint Search(const double array[], int size, double key) {

bool found = false; for(int i = 0; i < size; i++){ if(array[i] == key) { found = true; // record success

return i; }}if(!found) // report failure{ return -1;}

}

Page 17: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Pre- and Postconditions?Pre- and Postconditions?int Search(const double array[], int size, double key)

// PRE: Assigned(array[0..size-1])// && Assigned(key)// POST: If key is found in array,// function returns index// such that array[FCTVAL] == key// Otherwise, function returns -1{ // code goes here}

Page 18: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

A Slightly Improved FormA Slightly Improved Formint Search(const double array[], int size, double key) // PRE: Assigned(array[0..size-1]) && Assigned(key)// POST: If key is found in array, function returns index// such that array[FCTVAL] == key// Otherwise, function returns -1{

for(int i = 0; i < size; i++) // go through array{ // looking for key if(array[i] == key) // when it’s found { // return its index return i; // and leave function }}

return -1; // if the loop completes, the key // isn’t found, so report error // condition (-1)

}

Page 19: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Exercise for laterExercise for later Write the same search using a while loop

instead.

Why does the “slightly improved form” on the last slide work?

Page 20: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Linear Search OverviewLinear Search Overview The searching algorithm we’ve just looked at is

called the linear search or sequential search. General idea:

Compare search key to every element of the array. When key is found, save location and quit

successfully. If key isn’t found after checking all elements,

report failure.

Page 21: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Another Method: Another Method: The Binary SearchThe Binary Search

If we have a sorted array, we can take a different approach to searching called the binary search.

The binary search allows us to narrow our search field by half at each iteration.

We compare the key to the middle element. We could find the key there success. We otherwise eliminate half of the array and

search the other half.

Page 22: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Binary Search ExampleBinary Search Example

-9 -2 -1 0 3 5 7 17 25

using size == 9 for illustration purposes and searching for key == 5

-9 -2 -1 0 3 5 7 17 25Compare key to middle element…

-9 -2 -1 0 3 5 7 17 25It can’t be in the first half; eliminate first half and compare to middle of what remains

-9 -2 -1 0 3 5 7 17 25

-9 -2 -1 0 3 5 7 17 -9Can’t be 7 or anything greater; eliminate those elements and compare again

-9 -2 -1 0 3 5 7 17 -95 is now the only thing remaining in the array. It is thus also the middle. Since the middle equals the key, we’ve successfully found our key.

Page 23: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Binary Search, Binary Search, a bit more formallya bit more formally

We need to know what part of the array we’re searching, so we introduce a few variables for important array indices: low mid high

Since these variables are array indices, they need to be integers.

Remember int arithmetic – if the middle falls between two integers, “the middle” is the lower of the two.

Again, these variables represent array indices, NOT the values stored there.

Page 24: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Example with the indicesExample with the indices

-9 -2 -1 0 3 5 7 17 25

yellow == low

-9 -2 -1 0 3 5 7 17 25Compare key to middle element…

-9 -2 -1 0 3 5 7 17 25It can’t be in the first half; eliminate first half and compare to middle of what remains

-9 -2 -1 0 3 5 7 17 25

-9 -2 -1 0 3 5 7 17 -9Can’t be 7 or anything greater; eliminate those elements and compare again

-9 -2 -1 0 3 5 7 17 -95 is now the only thing remaining in the array. It is thus also the middle. Since the middle equals the key, we’ve successfully found our key.

blue == highgreen == middle 0 1 2 3 4 5 6 7 8

Page 25: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Writing the CodeWriting the Code• How do we know when the search has failed?

• high and low indices cross

• Try to write the code:• Use the same function header from before: int Search(const double array[], int size, double key)

• As before, return the index or -1 to signify failure

Page 26: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

First set up the high and low as local First set up the high and low as local variables…variables…

int Search(const double array[], int size, double key)

{ int high = size-1; int low = 0; int mid;

}

Page 27: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Handle one iteration…Handle one iteration…int Search(const double array[], int size, double key) { int high = size-1; // high index – one less than size int low = 0; // low index – 0 for any array int mid; // middle index

mid = (high+low)/2; // find middle index if(key == array[mid]) // compare to middle { return mid; // successful case } else if(key < array[mid]) // key is in first half { // eliminate second half high = mid-1; } else if(key > array[mid]) // key is in second half { // eliminate first half low = mid+1; }}

Page 28: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Handle multiple iterationsHandle multiple iterationsint Search(const double array[], int size, double key) { int high = size-1; // high index – one less than size int low = 0; // low index – 0 for any array int mid; // middle index

while(low <= high) // search until low and high cross {

mid = (high+low)/2; // find middle index if(key == array[mid]) // compare to middle { return mid; // successful case } else if(key < array[mid]) // key is in first half { // eliminate second half high = mid-1; } else if(key > array[mid]) // key is in second half { // eliminate first half low = mid+1; }

}}

Page 29: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Handle failed searchHandle failed searchint Search(const double array[], int size, double key) { int high = size-1; // high index – one less than size int low = 0; // low index – 0 for any array int mid; // middle index

while(low <= high) // search until low and high cross {

mid = (high+low)/2; // find middle index if(key == array[mid]) // compare to middle { return mid; // successful case } else if(key < array[mid]) // key is in first half { // eliminate second half high = mid-1; } else if(key > array[mid]) // key is in second half { // eliminate first half low = mid+1; }

} return -1; // if loop completes, search failed}

Page 30: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

Exercise for laterExercise for later Try to write the binary search using recursion.

Page 31: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

A Word about Running TimeA Word about Running Time How many times do we need to do

comparisons? OR How many iterations of the loops do we run?

Linear search If we have an array of n elements, we have to look

at all of the elements before saying the search failed.

We could do fewer if we’re successful sooner. We could do as many as n iterations of the loop.

Page 32: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

A Word about Running TimeA Word about Running Time Binary search

We do far fewer comparisons since we divide the number of elements by 2 each time

ex: 8 8 / 2 = 4 4 / 2 = 2 2 / 2 = 1 three comparisons

The number of comparisons could be as many as log2 n, often written lg n

ex: 23 = 8, lg 8 = 3

Page 33: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

More exercises for laterMore exercises for later How many iterations does the linear search do for an

array of size 128? How many iterations does the binary search do? Explain.

Given the array-3 13 23 42 51 60 61 99 Trace the execution of the linear search for 61. Trace the execution of the binary search for 61. Repeat using another key.

Think about how the linear search algorithm could be extended to sort an array.

Page 34: Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan

SummarySummary Linear search

Compare search key to every element of the array. When key is found, save location and quit successfully. If key isn’t found after checking all elements, report failure.

Binary search Compare search key to middle element. If they match,

report success. Eliminate half of the array based on whether key is larger or

smaller and repeat until high and low bounds cross. When high/low bounds cross, report failure.

Binary search is faster. For n elements, Linear search worst case running time is n Binary search worst case running time is lg n