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

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Search and Recursion pt. 2 CS221 – 2/25/09. How to Implement Binary Search Take a sorted data-set to search and a key to search for Start at the mid-point.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Searching Arrays. COMP104 Lecture 22 / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and return its index if the.
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
Efficiency of Algorithms Csci 107 Lecture 8. Last time –Data cleanup algorithms and analysis –  (1),  (n),  (n 2 ) Today –Binary search and analysis.
 Last lesson  Arrays for implementing collection classes  Performance analysis (review)  Today  Performance analysis  Logarithm.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Searching Arrays Linear search Binary search small arrays
Searching1 Searching The truth is out there.... searching2 Serial Search Brute force algorithm: examine each array item sequentially until either: –the.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
1 Search Algorithms Sequential Search (Linear Search) Binary Search Rizwan Rehman Centre for Computer Studies Dibrugarh University.
Chapter 8 ARRAYS Continued
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
CPT: Search/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss searching: its implementation,
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Today  Table/List operations  Parallel Arrays  Efficiency and Big ‘O’  Searching.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
SEARCHING (Linear/Binary). Searching Algorithms  method of locating a specific item of information in a larger collection of data.  two popular search.
Starting Out with C++, 3 rd Edition 1 Searching an Arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
COMP102 Lab 121 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Searching. RHS – SOC 2 Searching A magic trick: –Let a person secretly choose a random number between 1 and 1000 –Announce that you can guess the number.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
Pointers OVERVIEW.
CSC 211 Data Structures Lecture 13
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CSE 103, Penn State University Monday, November 4, 2002 prepared by Doug Hogan.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Sorting & Searching Review. Selection Sort 1. Find the smallest element 2. Move to the front of the array (swap with front) 3. Repeat Steps 1&2, but ignoring.
CS Class 22 Today  A word from the Real World What happens when software goes bad…  Binary Search Announcements  Exam 3 – Nov. 25 th in class.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Spring 2006CISC101 - Prof. McLeod1 Announcements Assn 4 is posted. Note that due date is the 12 th (Monday) at 7pm. (Last assignment!) Final Exam on June.
Data Structures Arrays and Lists Part 2 More List Operations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Searching Arrays Linear search Binary search small arrays
Recursion Version 1.0.
COP 3503 FALL 2012 Shayan Javed Lecture 15
Announcements HW6 due this Wednesday
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Announcements Final Exam on August 17th Wednesday at 16:00.
Introduction to Programming
Binary Search Example with Labeled Indices
Chapter 8 Search and Sort
Searching and Sorting Arrays
Announcements HW6 due this Wednesday
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
Search,Sort,Recursion.
Search,Sort,Recursion.
Chapter 18 Recursion.
Presentation transcript:

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

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

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.

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

Warm-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;

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; }

Output from Previous… For one sample set of data:

Printing Selectively Suppose we wanted to print out the array again, this time displaying just the positive values: for(int i = 0; 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.

Searching for a Specific Value 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.

Search, 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

Adding 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.

Adding Some Error Handling bool 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.”; }

Generalizing 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

More 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)

Adding 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

Search Function int 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; }

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 }

A Slightly Improved Form 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 { 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) }

Exercise for later Write the same search using a while loop instead. Why does the “slightly improved form” on the last slide work?

Linear 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.

Another Method: The 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.

Binary Search Example using size == 9 for illustration purposes and searching for key == Compare key to middle element… It can’t be in the first half; eliminate first half and compare to middle of what remains Can’t be 7 or anything greater; eliminate those elements and compare again 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.

Binary Search, a 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.

Example with the indices yellow == low Compare key to middle element… It can’t be in the first half; eliminate first half and compare to middle of what remains Can’t be 7 or anything greater; eliminate those elements and compare again 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 == high green == middle

Writing 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

First set up the high and low as local variables… int Search(const double array[], int size, double key) { int high = size-1; int low = 0; int mid; }

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; } }

Handle multiple iterations 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 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; } } }

Handle failed search 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 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 }

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

A 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.

A 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 log 2 n, often written lg n ex: 2 3 = 8, lg 8 = 3

More 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 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.

Summary 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