1 Techniques of Programming CSCI 131 Lecture 29 Search.

Slides:



Advertisements
Similar presentations
1 Arrays … The Sequel Applications and Extensions Chapter 10.
Advertisements

Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
Programming Searching Arrays. COMP102 Prog. Fundamentals: Searching Arrays/ Slide 2 Copyright © 2000 by Broks/Cole Publishing Company A division of International.
Abstract Data Types Applied Arrays: Lists and Strings Chapter
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
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.
1 Lab Session-XI CSIT121 Fall 2000 b Arrays and Their Usage b Finding the largest element b Lab Exercise 11-A b Searching for some value b Lab Exercise.
1 Lecture 15 Chapter 6 Looping Dale/Weems/Headington.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Chapter 6 Looping Dale/Weems. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Searching Arrays Linear search Binary search small arrays
1 Search Algorithms Sequential Search (Linear Search) Binary Search Rizwan Rehman Centre for Computer Studies Dibrugarh University.
CS161 Topic #14 1 Today in CS161 Lecture #14 Practicing! Writing Programs to Practice Write a program that counts the number of vowels in a sentence, ended.
1 Applied Arrays: Lists and Strings. 2 Chapter 13 Topics  Meaning of a List  Insertion and Deletion of List Elements  Selection Sort of List Elements.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 6 Looping.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.
CPT: Search/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss searching: its implementation,
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
Data Structures Using C++1 Search Algorithms Sequential Search (Linear Search) Binary Search.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
Starting Out with C++, 3 rd Edition 1 Searching an Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Lecture 16: Searching and Sorting Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
Required Functions for Program 3 int readUntilValidBaseRead( ); int readNumbersReturningValue( int base ); int decimalValueOf( char chDigit ); bool isValid(
CSC 211 Data Structures Lecture 13
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 6 Looping. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
Review Binary Numbers Bit : 0 or 1 Byte: 8 bites 256 different values 2 8 KB : 1024 bytes 2 10 bytes MB : 1024 * 1024 bytes 2 10 * 2 10 (2 20 ) bytes GB.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
No I/O is built into C++ l instead, a library provides input stream and output stream KeyboardScreen executing program istreamostream 1.
1 Chapter 12-2 Arrays Dale/Weems. 2 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information n.
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
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.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Fall 1999CS Composite Data Types. Fall 1999CS Topics to be Covered l Abstract data types l One-dimensional arrays l Two-dimensional arrays.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
1 Chapter 13 Applied Arrays: Lists and Strings Dale/Weems/Headington.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
Fundamental Programming Fundamental Programming Introduction to Functions.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 19: Container classes; strings.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
Searching Arrays Linear search Binary search small arrays
Chapter 6 Looping.
Chapter 13 Applied Arrays: Lists and Strings
The Sequential Search (Linear Search)
Arrays … The Sequel Applications and Extensions
String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string.
No I/O is built into C++ instead, a library provides input stream and output stream Keyboard Screen executing program istream ostream 1.
Chapter 13 Applied Arrays: Lists and Strings
The Sequential Search (Linear Search)
The Sequential Search (Linear Search)
Presentation transcript:

1 Techniques of Programming CSCI 131 Lecture 29 Search

2 Sequential Search in C++ void search(int myArray[ ], int length, int item, bool& found, int& index) { index = 0; found = false; while ((!found) && (index < length)) { if (myArray[index] == item) found = true; else index++; } //while not found and not at end of list return; } //end search lookup

3 Calling Sequential Search int main(void) { int myArray[5] = {17, 4, 12, 9, 2}; int length = 5; int item; bool found; int where; cout << "Enter an item to search for: " << endl; cin >> item; search(myArray, length, item, found, where); if (found) cout << item << " found at index " << where << endl; else cout << item << " not found in list. " << endl; return 0; } //end main

4 Programming Example Write a program that will: 1) Read the ID numbers, hourly wages, and names, for up to 50 persons from a data file. 2) Then display the ID number and hourly wage for any person in the file whose name is entered at the keyboard, or indicate that the person was not located, if that is the case.

5 Input File Format Dale Nell Weems Chip Headington Mark Laurie King Stanzi Royden Assume no more than 50 persons in the file

6 An array of struct s const int MAX_PERSONS = 50; typedef char String20[21] ; // define data type struct Person { int idNum; float wages; String20 name; };. Person people[MAX_PERSONS];

7 struct Person { int idNum; float wages; Person people[MAX_PERSONS]; String20 name; }; 5 people[0] “Dale Nell” people[1] “Weems Chip” people[2] “Headington Mark”.... people[48] “Laurie King” people[49] “Stanzi Royden”

8 Organization of Program Main GetData LookUp HandleRequests people oneName numPersons people numPersons people numPersons found index

9 The Preliminaries #include using namespace std; typedef char String20 [ 21 ] ; const int MAX_PERSONS = 50 ; struct Person { int idNum; float wages; String20 name; }; void GetData (Person[], int &) ; // prototypes void HandleRequests (Person[], int) ; void LookUp (Person[], String20, int, bool &, int &);

10 The main( ) Program int main (void) { Person people[MAX_PERSONS]; // holds up to 50 Person s int numPersons; // number of person s’ information in file GetData ( people, numPersons ) ; HandleRequests (people, numPersons ) ; cout << “End of Program.\n”; return 0 ; } // end main

void GetData ( /* out */ Person people[], /* out */ int & howMany ) { ifstream myInfile ; // Reads data from data file int k = 0 ; char ch ; myInfile.open (“myFile.dat”) ; if (!myInfile) { cout << “File opening error. Program terminated!“ << endl ; exit ( 1 ) ; } // end file in fail state // get id for first person -- prime the read, if there's an id, get the rest myInfile >> people[k].idNum; while (myInfile) { // while the last read was successful myInfile >> people[k].wages; myInfile.get(ch); // read blank myInfile.get (people[k].name, 21); myInfile.ignore(30, ‘\n’); // consume newline k++ ; // get id for next person myInfile >> people[k].idNum; } // end getting information from the file howMany = k; return; } // end getData

void HandleRequests(const /*in */ Person people[], /* in */ int numPersons) { String20 oneName ; // string to hold name of one person int index ; // will hold an array index value char response; // user’s response whether to continue bool found; // has oneName been located in array names do { cout << “Enter name of person to find: ” ; cin.get (oneName, 21) ; cin.ignore (100, ‘\n’); // consume newline LookUp(people, oneName, numPersons, found, index ); if ( found ) cout << oneName << “ has ID #“ << people[index].idNum << “ and hourly wage $ “ << people[index].wages << endl; else cout << oneName << “ was not located. “ << endl; cout << “Want to find another (Y/N)? “; cin >> response ; response = toupper ( response ); } while ( response == ‘Y’ ); return; } // end HandleRequests

void LookUp ( const /* in */ Person people[ ], const /* in */ String20 oneName, /* in */ int numPersons, /*out */ bool &found, /*out */ int &index) // Sequential search of unordered array. // POSTCONDITION: // IF oneName is in names array // found == true && names[index] == oneName // ELSE // found == false && index == numPersons { index = 0; found = false; // initialize flag while ((!found) && (index < numPersons)) { // more to search if (strcmp (oneName, people[index].name) == 0) found = true ; // have a match, so change flag else index ++ ; } // while oneName not found and still more list to search return; } // end LookUp

14 Sequential Search In a sequential search, the elements in the list are examined in order until the desired item is found. Sequential searches are often used with un-ordered lists.

15 Assume that numPersons has value 50. How many actual names in the array names must be examined before determining that oneName was not located? What are some ways to “speed up” this process? Some Questions 0 Dale Nell 1 Weems Chip 2 Headington Mark King Laurie 49 Royden Stanzi Suppose MAX_PERSONS is later changed to How many actual names in the array names would need to be examined to determine that oneName cannot be located?

16 Ways to improve efficiency of searching process æ If the array names were sorted, the sequential search for oneName could be aborted as soon as a single name with greater lexicographic (dictionary) order is examined. æ If the array names were sorted, a faster type of search, called a binary search, could be used instead of the slower sequential search.

17 Binary Search in an Ordered Array Examines the element in the middle of the array. Is it the sought item? If so, stop searching. Is the middle element too small? Then start looking in second half of array. Is the middle element too large? Then begin looking in first half of the array. Repeat the process in the half of the list that should be examined next. Stop when item is found, or when there is nowhere else to look and it has not been located.

18 Pseudocode for Binary Search Set first = 0 Set last = length - 1 Set found = FALSE WHILE last >= first and not found Set middle = (first + last) / 2 IF the_item_to_find < list[middle] Set last = middle - 1 ELSE IF the item to find > list[middle] Set first = middle + 1 ELSE Set found = TRUE

19 Trace of Binary Search item = 45 list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first middle last item < list [ middle ] last = middle - 1 list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first middle last item > list [ middle ] first = middle + 1

20 Trace Continued item = 45 item > list [ middle ] first = middle + 1 item < list [ middle ] last = middle - 1 list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first, last middle list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first, middle, last

21 Trace Concludes item = 45 last first last < first found = false list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]