C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 10: Applications of Arrays (Searching and Sorting) and the vector Type.

Slides:



Advertisements
Similar presentations
Chapter 10: Applications of Arrays and the class vector
Advertisements

C++ Programming:. From Problem Analysis
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Advanced Array Manipulation
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 9: Searching, Sorting, and Algorithm Analysis
CHAPTER 10 ARRAYS II Applications and Extensions.
Chapter 19: Searching and Sorting Algorithms
Searches & Sorts V Deena Engel’s class Adapted from W. Savitch’s text An Introduction to Computers & Programming.
1 Lecture 23:Applications of Arrays Introduction to Computer Science Spring 2006.
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
Introduction to Programming with C++ Fourth Edition
C++ for Engineers and Scientists Third Edition
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Chapter 8 Arrays and Strings
Programming Logic and Design Fourth Edition, Comprehensive
1 Lecture 22:Applications of Arrays Introduction to Computer Science Spring 2006.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Chapter 16: Searching, Sorting, and the vector Type.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Chapter 8 Arrays and Strings
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 19: Searching and Sorting Algorithms.
Chapter 10 Applications of Arrays and Strings. Chapter Objectives Learn how to implement the sequential search algorithm Explore how to sort an array.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
Applications of Arrays (Searching and Sorting) and Strings
Chapter 19: Searching and Sorting Algorithms
Computer Science Searching & Sorting.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CSC 211 Data Structures Lecture 13
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Computer Science: A Structured Programming Approach Using C1 8-7 Two-Dimensional Arrays The arrays we have discussed so far are known as one- dimensional.
Chapter 14: Searching and Sorting
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 2.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
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.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Computer Science: A Structured Programming Approach Using C1 8-7 Two-Dimensional Arrays The arrays we have discussed so far are known as one- dimensional.
Chapter 10: Class Vector and String, and Enumeration Types Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
CHAPTER 10 ARRAYS II Applications and Extensions.
Data Structures Using Java1 Chapter 9 Sorting Algorithms.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
Chapter 16: Searching, Sorting, and the vector Type.
Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings.
Searching and Sorting Arrays
Chapter 16: Searching, Sorting, and the vector Type
Chapter 9: Sorting and Searching Arrays
Data Structures I (CPCS-204)
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
24 Searching and Sorting.
Searching and Sorting Arrays
Applications of Arrays
Presentation transcript:

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 10: Applications of Arrays (Searching and Sorting) and the vector Type

C++ Programming: From Problem Analysis to Program Design, Third Edition2 Objectives In this chapter you will: Learn how to implement the sequential search algorithm Explore how to sort an array using the bubble sort, selection sort, and insertion sort algorithms Learn how to implement the binary search algorithm Become familiar with the vector type

C++ Programming: From Problem Analysis to Program Design, Third Edition3 List Processing List: a set of values of the same type Basic list operations: 1.Search for a given item 2.Sort the list 3.Insert an item in the list 4.Delete an item from the list

C++ Programming: From Problem Analysis to Program Design, Third Edition4 Searching To search a list, you need 1.The list (array) containing the list 2.List length 3.Item to be found After the search is completed 4.If found, Report “success” Location where the item was found 5.If not found, report “failure”

C++ Programming: From Problem Analysis to Program Design, Third Edition5 Sequential Search Sequential search: search a list for an item Compare search item with other elements until either −Item is found −List has no more elements left Average number of comparisons made by the sequential search equals half the list size Good only for very short lists

C++ Programming: From Problem Analysis to Program Design, Third Edition7 Sorting a List: Bubble Sort Suppose list[0]...list[n - 1] is a list of n elements, indexed 0 to n – 1 Bubble sort algorithm: −In a series of n - 1 iterations, compare successive elements, list[index] and list[index + 1] −If list[index] is greater than list[index + 1], then swap them

C++ Programming: From Problem Analysis to Program Design, Third Edition12 Sorting a List: Selection Sort Selection sort: rearrange list by selecting an element and moving it to its proper position Find the smallest (or largest) element and move it to the beginning (end) of the list

C++ Programming: From Problem Analysis to Program Design, Third Edition13 Sorting a List: Selection Sort (continued) On successive passes, locate the smallest item in the list starting from the next element

C++ Programming: From Problem Analysis to Program Design, Third Edition16 Sorting a List: Insertion Sort The insertion sort algorithm sorts the list by moving each element to its proper place.

C++ Programming: From Problem Analysis to Program Design, Third Edition22 Sequential Search on an Ordered List General form of sequential search algorithm on a sorted list:

C++ Programming: From Problem Analysis to Program Design, Third Edition26 Binary Search Binary search can be applied to sorted lists Uses the “divide and conquer” technique −Compare search item to middle element −If search item is less than middle element, restrict the search to the lower half of the list −Otherwise search the upper half of the list

C++ Programming: From Problem Analysis to Program Design, Third Edition30 Binary Search (continued) Every iteration cuts size of search list in half If list L has 1000 items −At most 11 iterations needed to determine if an item x is in list Every iteration makes 2 key (item) comparisons −Binary search makes at most 22 key comparisons to determine if x is in L Sequential search makes 500 key comparisons (average) to if x is in L for the same size list

C++ Programming: From Problem Analysis to Program Design, Third Edition31 vector Type (class) C++ provides vector type to implement a list Variables declared with vector type are called −vector container −Vector −vector object −object Unlike arrays, vector size can increase and decrease during execution

C++ Programming: From Problem Analysis to Program Design, Third Edition36 Programming Example Student council of your local university will hold presidential election soon For reasons of confidentiality, election committee wants to computerize the voting The committee needs a program to analyze the data and report the winner The university has four major divisions and each division has several departments

C++ Programming: From Problem Analysis to Program Design, Third Edition37 Programming Example (continued) For the purpose of the election, the divisions are labeled as Region 1 - Region 4 Each department in each division manages its own voting process and directly reports the votes to the election committee The voting is reported in the following form: −candidate_name −region# −number_of_votes_for_this_candidate

C++ Programming: From Problem Analysis to Program Design, Third Edition38 Programming Example (continued) The data are provided in two files −One file has candidate names seeking the president’s post (unordered) −Each line of second file consists of voting results in the following form: candidateName regionNumber numberOfVotesForThisCandidate

C++ Programming: From Problem Analysis to Program Design, Third Edition39 Input and Output For example, assume the input file looks like: Mia 2 34 Mickey 1 56 Donald 2 56 Mia 1 78 Danny 4 29 Ashley 4 78 The first line indicates that Mia received 34 votes from region 2 Output consists of election results in tabular form as described and identifies the winner

C++ Programming: From Problem Analysis to Program Design, Third Edition40 Problem Analysis Program must organize voting data by region Calculate total number of votes received by each candidate and total votes cast Candidate names must be alphabetized Data types −Candidate name: string −Number of votes: integer

C++ Programming: From Problem Analysis to Program Design, Third Edition41 Problem Analysis (continued) Need two arrays Candidate names: 1-d array of strings Use a two-dimensional array to hold the next four columns of the output and a one- dimensional array to hold the total votes received by each candidate These three arrays are parallel arrays

C++ Programming: From Problem Analysis to Program Design, Third Edition42 Algorithm Design 1.Read candidate names into the array candidatesName 2.Sort candidatesName 3.Initialize votesByRegion and totalVotes 4.Process the voting data 5.Calculate total votes received by each candidate 6.Output the results

C++ Programming: From Problem Analysis to Program Design, Third Edition43 Process Voting Data For each entry in voteDat.txt : 1.Get a candidateName, regionNumber, numberOfVotesForTheCandidate 2.Find the row number in the array candidatesName corresponding to this candidate This gives the corresponding row number in the array votesByRegion for this candidate

C++ Programming: From Problem Analysis to Program Design, Third Edition44 Process Voting Data (continued) 3.Find the column in the array votesByRegion corresponding to the regionNumber 4.Update the appropriate entry in votesByRegion by adding numberOfVotesForTheCandidate

C++ Programming: From Problem Analysis to Program Design, Third Edition45 Function printResults Initialize sumVotes, largestVotes, winLoc to 0 For each row in each array if (largestVotes < tVotes[i]) { largestVotes = tVotes[i]; winLoc = i; } sumVotes = sumVotes + tVotes[i]; Output from corresponding rows of arrays Output the final lines of output

C++ Programming: From Problem Analysis to Program Design, Third Edition46 Main Algorithm: Function main 1.Declare the variables 2.Open the input file candDat.txt 3.If input file does not exist, exit program 4.Read data from candDat.txt into the array candidatesName 5.Sort the array candidatesName

C++ Programming: From Problem Analysis to Program Design, Third Edition47 Main Algorithm: Function main (continued) 6.Close candDat.txt 7.Open the input file voteDat.txt 8.If input file does not exist, exit program 9.Initialize votesByRegion and totalVotes 10.Process voting data and store results in votesByRegion

C++ Programming: From Problem Analysis to Program Design, Third Edition48 Main Algorithm: Function main (continued) 11.Calculate total votes received by each candidate and store results in totalVotes 12.Print the heading 13.Print the results

C++ Programming: From Problem Analysis to Program Design, Third Edition49 Summary List: set of elements of the same type List length: number of elements Sequential search algorithm: −Search for an item, starting at first element −Compare search item with other elements −Stop when item is found, or list has no more elements left to be compared Searches half the list (average) Good only for very short lists

C++ Programming: From Problem Analysis to Program Design, Third Edition50 Summary (continued) Bubble sort sorts by moving the largest elements toward the bottom Selection sort sorts by finding the smallest (or largest) element and moving it to the beginning (end) of the list Binary search is much faster than sequential search, but requires an ordered list

C++ Programming: From Problem Analysis to Program Design, Third Edition51 Summary (continued) C++ provides vector type to implement lists Vector size can increase or decrease Vector object must specify the type of element the vector object stores First element in vector is at location 0 Vector class includes various functions