• No results found

C++ Programming: From Problem Analysis to Program Design, Fifth Edition

N/A
N/A
Protected

Academic year: 2020

Share "C++ Programming: From Problem Analysis to Program Design, Fifth Edition"

Copied!
60
0
0

Loading.... (view fulltext now)

Full text

(1)

C++ Programming: From Problem Analysis to

Program Design, Fifth Edition

Chapter 10:

Applications of Arrays and the class

(2)

Objectives

In this chapter, you will:

• 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

(3)

List Processing

• List: a collection of values of the same

type

• Basic list operations:

– Search the list for a given item

– Sort the list

– Insert an item in the list

– Delete an item from the list

– Print the list

(4)

Searching

• Sequential search algorithm

(5)

Searching (cont'd.)

• List with 1000 elements

– Search item is the second item

• Sequential search makes two key comparisons

– Search item is the 900th item

• Sequential search makes 900 key comparisons

– Search item is not in the list

• Sequential search makes 1000 key comparisons

(6)

Searching (cont'd.)

• Sequential search

– Not very efficient for large lists

– On average, number of key comparisons

equal to half the size of the list

– Does not assume that the list is sorted

(7)

Bubble Sort

list[0]...list[n - 1]

– List of n elements, indexed 0 to n - 1

(8)

Bubble Sort (cont'd.)

• Series of

n - 1

iterations

– Successive elements

list[index]

and

list[index + 1]

of

list

are compared

– If

list[index]

>

list[index + 1]

• Elements

list[index]

and

list[index + 1]

are swapped

• Smaller elements move toward the top

• Larger elements move toward the bottom

(9)

Bubble Sort (cont'd.)

(10)

Bubble Sort (cont'd.)

(11)

Bubble Sort (cont'd.)

(12)

Bubble Sort (cont'd.)

(13)

Bubble Sort (cont'd.)

(14)

Bubble Sort (cont'd.)

• List of length

n

– Exactly

n

(

n -

1) / 2 key comparisons

– On average

n

(

n -

1) / 4 item assignments

• n

= 1000

– 500,000 key comparisons

– 250,000 item assignments

(15)

Selection Sort

• Rearrange the list by selecting an element

in the list and moving it to its proper

position

• Finds the location of the smallest element

in the unsorted portion of the list

– Moves it to the top of the unsorted portion of

the list

(16)

Selection Sort (cont'd.)

(17)

Selection Sort (cont'd.)

(18)

Selection Sort (cont'd.)

• In the unsorted portion of the list:

– Find the location of the smallest element

– Move the smallest element to the beginning of

the unsorted list

(19)

Selection Sort (cont'd.)

(20)

Selection Sort (cont'd.)

• List of length

n

– Exactly

n

(

n -

1

)

/ 2

key comparisons

– 3(

n -

1

)

item assignments

• n

= 1000

– 500,000 key comparisons

– 3000 item assignments

(21)

Insertion Sort

• Sorts the list by moving each element to

its proper place

(22)

Insertion Sort (cont'd.)

• Consider the element

list[4]

– First element of unsorted list

list[4] < list[3]

• Move

list[4]

to proper location

• At

list[2]

(23)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 23

(24)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24

(25)

Insertion Sort (cont'd.)

• During the sorting phase

– Array containing the list is divided into two

sublists: sorted and unsorted

(26)

Insertion Sort (cont'd.)

(27)

Insertion Sort (cont'd.)

• List of length

n

– About (

n

2

+

3

n –

4) / 4 key comparisons

– About

n

(

n –

1) / 4 item assignments

• n

= 1000

– 250,000 key comparisons

– 250,000 item assignments

(28)

Binary Search

• Much faster than a sequential search

• List must be sorted

• “Divide and conquer”

• Compare search item with middle element

– Less than middle: search only upper half of list

– More than middle: search only lower half of list

(29)

Binary Search (cont'd.)

(30)

Binary Search (cont'd.)

(31)

Binary Search (cont'd.)

(32)

Performance of Binary Search

• L

is a sorted list of size 1024

– Every iteration of the

while

loop cuts the size

of the search list by half

– At most, 11 iterations to determine whether

x

is in

L

– Binary search will make 22 comparisons at

most

• L has1048576 elements

– Binary search makes 42 item comparisons at

most

(33)

Performance of Binary Search

(cont'd.)

• List of length

n

– Maximum number comparisons 2log

2

n

+ 2

(34)

vector type (class)

• Only a fixed number of elements can be

stored in an array

• Inserting and removing elements causes

shifting

vector

type implements a list

vector

container

vector

vector object

object

(35)

vector type (class) (cont'd.)

(36)

vector type (class) (cont'd.)

(37)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37

(38)

vector type (class) (cont'd.)

(39)

Programming Example: Election

Results

• Presidential election for the student council of

your local university

• Write a program to analyze the data and

report the winner

• Four major divisions labeled as Region 1,

Region 2, Region 3, and Region 4

– Each division has several department

– Each department manages its own voting process

and directly reports the results to the election

committee

(40)

Programming Example: Election

Results (cont'd.)

• Desired output:

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 40

(41)

Programming Example: Election

Results (cont'd.)

• Assume that six candidates are running

– Program can be modified to accommodate

any number of candidates

• Data is provided in two files:

candData.txt

consists of the names of

candidates

voteData.txt

each line consists of voting

results

• One entry per line

(42)

Programming Example: Input and

Output

• Input: Two files, one containing the

candidates’ names and the other

containing the voting data

• Output: election results in a tabular form

and the winner

(43)

Programming Example: Problem

Analysis

• Program must organize the voting data by

region

• Program must calculate total number of

votes received by each candidate as well

as the total votes cast in the election

• Names of the candidates must appear in

alphabetical order

(44)

Programming Example: Problem

Analysis (cont'd.)

• Data type of a candidate’s name and

number of votes are different

– Separate arrays

• Use a two-dimensional array to hold the

next four columns of the output

• One-dimensional array to hold the total

votes received by each candidate

(45)

Programming Example: Problem

Analysis (cont'd.)

(46)

Programming Example: Algorithm

Design

• Read the candidates’ names into the array

candidatesName

• Sort the array

candidatesName

• Initialize the arrays

votesByRegion

and

totalVotes

• Process the voting data

• Calculate the total votes received by each

candidate

• Output the results

(47)

Programming Example: Function

getCandidatesName()

(48)

Programming Example: Function

sortCandidateName()

(49)

Programming Example: Function

initialize()

(50)

Programming Example: Process

Voting Data

• Get a

candidateName

,

regionNumber

,

and

numberOfVotesForTheCandidate

• Find the row number in the array

candidatesName

that corresponds to this

candidate

– This gives the corresponding row number in the

array

votesByRegion

for this candidate

• Find the column in the array

votesByRegion

that corresponds to the

regionNumber

(51)

Programming Example: Process

Voting Data

(cont'd.)

• Update the appropriate entry in the array

votesByRegion

by adding the

numberOfVotesForTheCandidate

(52)

Programming Example: Function

binSearch()

(53)

Programming Example: Function

processVotes()

(54)

Programming Example: Function

addRegionsVote()

(55)

Programming Example: Function

printHeading()

(56)

Programming Example: Function

printResults()

• Initialize

sumVotes

,

largestVotes

, and

winLoc

to 0

• For each row in each array:

• Output the final lines of output

(57)

Programming Example: Main

Algorithm

• Declare the variables

• Open the input file

candData.txt

• If the input file does not exist, exit the

program

• Read the data from the file

candData.txt

into the array

candidatesName

• Sort the array

candidatesName

• Close the file

candData.txt

and clear the

input stream

(58)

Programming Example: Main

Algorithm (cont'd.)

• Open the input file

voteData.txt

• If the input file does not exist, exit the

program

• Initialize the arrays

votesByRegion

and

totalVotes

• Process the voting data and store the

results in the array

votesByRegion

(59)

Programming Example: Main

Algorithm (cont'd.)

• Calculate the number of total votes

received by each candidate and store the

results in the array

totalVotes

• Print the heading

• Print the results

(60)

Summary

• List

– Set of elements of the same type

• Sorting algorithms

– Bubble sort

– Selection sort

– Insertion sort

• Binary search

– Compare performance to sequential search

vector

type

References

Related documents

Although promotion is not done only for these factors but for other such as to build brand loyalty, to reminds and reassure costumers, to launch a new product and maybe to

In addition to Conference, General Church and Jurisdictional Church Apportionments, each District apportions monies to support missions, ministries, programs and administration

• The syntax of an input statement using cin and the extraction operator &gt;&gt; is:4. • The extraction operator &gt;&gt;

Systems Analysis and Design in a Changing World, Fifth Edition3. Learning Objectives

We evaluate the performance of RAMMIE, Farrington Flexible and EARS by comparing the power of detection, sensitivity, specificity and timeliness using extensive simulations based

May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on

186. In fiscal year 2002, the federal government arrested 510 unauthorized workers and employers in workplace raids. Immigration &amp; Customs Enforcement, supra note 180.. asserted

User guide to help in installation, operation and maintenance of Item Location mapping software. User Guide for Item Motion