CHAPTER 10 ARRAYS II Applications and Extensions - PowerPoint PPT Presentation

1 / 117
About This Presentation
Title:

CHAPTER 10 ARRAYS II Applications and Extensions

Description:

... faefaffafafadedfdeOeOTdF F Fs SS pp G G SG a aSeeeeffdddOdOT ... ' ' D :' : : P ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 118
Provided by: abc751
Category:

less

Transcript and Presenter's Notes

Title: CHAPTER 10 ARRAYS II Applications and Extensions


1
CHAPTER 10ARRAYS IIApplications and Extensions
2
  • In this chapter, you will
  • Learn how to implement the sequential search
    algorithm
  • Explore how to sort an array using the selection
    sort algorithm
  • Learn how to implement the binary search
    algorithm
  • Discover how to manipulate data in a
    two-dimensional array
  • Learn about multidimensional arrays

3
  • LIST PROCESSING
  • A list is defined as a set of values of the same
    type.
  • Some of the basic operations that are performed
    on a list are
  • 1. Search the list for a given item.
  • 2. Sort the list.
  • 3. Insert an item in the list.
  • 4. Delete an item from the list.

4
  • Searching
  • To search the list, you need three pieces of
    information
  • 1. The list, that is, the array containing the
    list.
  • 2. The length of the list.
  • 3. The item for which you are searching.
  • After the search is completed,
  • 4. If the item is found, then report success
    and the location where the item was found.
  • 5. If the item is not found, then report
    failure.
  • To accommodate 4 and 5, we will write a
    value-returning function.
  • If the search item is found in the list, the
    function returns the location in the list where
    the search item is found otherwise, it returns
    1.

5
  • The value-returning function has three
    parameters
  • 1. The array, list, containing the list.
  • 2. The length of the list, listLength.
  • 3. The item, searchItem, for which you are
    searching.

6
  • Sequential Search
  • Suppose that you want to determine whether 27 is
    in the list.
  • First, you compare 27 with list0that is,
    compare 27 with 35.
  • As list0 ? 27, you then compare 27 with
    list1.
  • As list1 ? 27, you compare 27 with the next
    element in the listthat is, compare 27 with
    list2.
  • Because list2 27, the search stops. This is a
    successful search.

7
  • Search for 10.
  • The search starts with the first element in the
    listthat is, at list0.
  • This time the search item, which is 10, is
    compared with every item in the list.
  • This is an unsuccessful search.

8
  • found is set to false
  • for(loc 0 loc lt length loc)
  • if(listloc is equal to searchItem)
  • found is set to true
  • exit loop
  • if(found)
  • return loc
  • else
  • return 1

9
  • int seqSearch(const int list, int listLength,
  • int searchItem)
  • int loc
  • bool found false
  • for(loc 0 loc lt listLength loc)
  • if(listloc searchItem)
  • found true
  • break
  • if(found)
  • return loc
  • else
  • return -1

10
  • If the function seqSearch returns a value greater
    than or equal to 0, it is a successful search
    otherwise, it is an unsuccessful search.

11
  • Suppose that you have a list with 1000 elements.
  • If the search item is the second item in the
    list, the sequential search makes 2 key (also
    called item) comparisons to determine whether the
    search item is in the list.
  • If the search item is the 900th item in the list,
    the sequential search makes 900 key comparisons
    to determine whether the search item is in the
    list.
  • If the search item is not in the list, the
    sequential search makes 1000 key comparisons.

12
  • A sequential search is not very efficient for
    large lists.
  • On average, the number of comparisons (key
    comparisonsnot index comparisons) made by the
    sequential search is equal to half the size of
    the list.
  • For a list size of 1000, on average, the
    sequential search makes about 500 key
    comparisons.
  • The preceding search algorithm does not assume
    that the list is sorted.
  • If the list is sorted, then you can somewhat
    improve the search algorithm.

13
  • Sorting a List Selection Sort
  • This algorithm finds the location of the smallest
    element in the unsorted portion of the list, and
    moves it to the top of the unsorted portion of
    the list.
  • The first time we locate the smallest item in the
    entire list, the second time we locate the
    smallest item in the list starting from the
    second element in the list, and so on.

14
  • Suppose that you have the following list.
  • Find the smallest item in the list, which is at
    position 7.
  • Because this is the smallest item, it must be
    moved to position 0

15
  • List after swapping
  • Now the unsorted list is list1...list9.

16
  • Find the smallest element in the unsorted portion
    of the list.
  • Swap list3 with list1

17
  • After swapping list1 with list3, the
    resulting list is
  • The process is repeated on list2...list9

18
  • In the unsorted portion of the list
  • a. Find the location of the smallest element.
  • b. Move the smallest element to the beginning of
    the unsorted list.
  • for(index 0 index lt length 1 index)
  • a. Find the location, smallestIndex, of the
    smallest element in listindex...listlength.
  • b. Swap the smallest element with listindex.
    That is, swap listsmallestIndex with
    listindex.

19
  • Step a
  • smallestIndex index //assume first element is
    the
  • //smallest
  • for(minIndex index 1 minIndex lt length
  • minIndex)
  • if(listminIndex lt listsmallestIndex)
  • smallestIndex minIndex //current element
    in
  • //the list is
    smaller than
  • //the smallest so far, so
  • //update smallestIndex
  • Step b
  • temp listsmallestIndex
  • listsmallestIndex listindex
  • listindex temp

20
  • Before writing the selection sort function, let
    us apply the above algorithm to sort the
    following list.

The length of list is 6
21
  • Iteration 1 Sort list0...list5.
  • Step a Find the index of the smallest element in
    list0...list5.

Step b Swap listsmallestIndex with
listindex, that is, list3 with list0. The
resulting array is
22
  • Iteration 2 Sort list1...list5. Here index
    1.
  • Step a Find the index of the smallest element in
    list1...list5.

Step b Swap listsmallestIndex with
listindex. That is, swap list1 with list1.
23
  • Iteration 3 Sort list2...list5.
  • Step a Find the index of the smallest element in
    list2...list5.

Step b Swap listsmallestIndex with
listindex. That is, swap list4 with list2.
24
  • Iteration 4 Sort list3...list5.
  • Step a Find the index of the smallest element in
    list3...list5.

Step b Swap listsmallestIndex with
listindex. That is, swap list3 with list3.
25
  • Iteration 5 Sort list4...list5.
  • Step a Find the index of the smallest element in
    list4...list5.

Step b Swap listsmallestIndex with
listindex. That is, swap list5 with list4.
26
  • void selectionSort(int list, int length)
  • int index
  • int smallestIndex
  • int minIndex
  • int temp
  • for(index 0 index lt length 1 index)
  • //Step a
  • smallestIndex index
  • for(minIndex index 1 minIndex lt
    length
  • minIndex)
  • if(listminIndex lt listsmallestIndex)
  • smallestIndex minIndex
  • //Step b
  • temp listsmallestIndex

27
  • Sequential search on a sorted list
  • found is set to false
  • for(loc 0 loc lt listLength loc)
  • if (listloc is greater than or equal to
  • searchItem)
  • found is set to true
  • exit loop
  • if(found)
  • if(listloc searchItem)
  • return loc
  • else
  • return 1
  • else

28
  • int seqOrderdSearch(const int list, int
    listLength,
  • int searchItem)
  • int loc //Line 1
  • bool found false //Line 2
  • for(loc 0 loc lt listLength loc) //Line 3
  • if(listloc gt searchItem) //Line 4
  • found true //Line 5
  • break //Line 6
  • if(found) //Line 7
  • if(listloc searchItem) //Line 8
  • return loc //Line 9
  • else //Line 10
  • return 1 //Line 11
  • else //Line 12

29
  • length 8 searchItem 35 loc 0, found
    false.
  • Iteration loc found listloc listlocgt
    searchItem
  • 1 0 false 4 4 gt 35 is false loc 1
  • 2 1 false 18 18 gt 35 is falseloc 2
  • 3 2 false 29 29 gt 35 is falseloc 3
  • 4 3 false 35 35 gt 35 is true found
    true

30
  • found is true, the if statement at Line 8
    executes.
  • listloc 35 and searchItem 35, the
    expression
  • listloc searchItem
  • evaluates to true and the return statement at
    Line 9 returns the value of loc, which is 3.
  • This is a successful search.

31
  • searchItem 40 loc 0 found false.
  • Iteration loc found listloc listlocgt
    searchItem
  • 1 0 false 4 4 gt 40 is false loc 1
  • 2 1 false 18 18 gt 40 is false loc 2
  • 3 2 false 29 29 gt 40 is false loc 3
  • 4 3 false 35 35 gt 40 is false loc 4
  • 5 4 false 44 44 gt 40 is true
  • found true

32
  • found is true. The if statement at Line 8
    executes.
  • listloc 44 and searchItem 40. The
    expression
  • listloc searchItem
  • evaluates to false, the statement at Line 9 is
    skipped, and the return statement at Line 11
    executes, which returns 1.
  • This is an unsuccessful search.

33
  • Binary Search
  • A binary search is similar to a dictionary
    search.
  • A binary search uses the divide and conquer
    technique to search the list.
  • First, the search item is compared with the
    middle element of the list.
  • If the search item is less than the middle
    element of the list, we restrict the search to
    the upper half of the list otherwise, we search
    the lower half of the list.
  • Consider the following sorted list of length 12

34
  • Determine whether 75 is in the list
  • Compare 75 with the middle element in the list,
    list5 (which is 39).
  • Because 75 ? list5 and 75 gt list5, we then
    restrict our search to the list list6...list11

35
  • int binarySearch(const int list, int
    listLength,
  • int searchItem)
  • int first 0
  • int last listLength - 1
  • int mid
  • bool found false
  • while(first lt last !found)
  • mid (first last) / 2
  • if(listmid searchItem)
  • found true
  • else
  • if(listmid gt searchItem)
  • last mid - 1

36
  • if(found)
  • return mid
  • else
  • return 1
  • //end binarySearch

37
  • searchItem 89 first 0, last 11, and found
    false
  • Iteration first last mid listmid Number of Key
    Comp.
  • 1 0 11 5 39 2
  • 2 6 11 8 66 2
  • 3 9 11 10 89 1 (found is true)
  • searchItem 34 first 0, last 11, and found
    false
  • Iteration first last mid listmid Number of Key
    Comp.
  • 1 0 11 5 39 2
  • 2 0 4 2 19 2
  • 3 3 4 3 25 2
  • 4 4 4 4 34 1 (found is true)

38
  • searchItem 22 first 0, last 11, and found
    false
  • Iteration first last mid listmid Number of Key
    Comp.
  • 1 0 11 5 39 2
  • 2 0 4 2 19 2
  • 3 3 4 3 25 2
  • 4 3 2 The loop stops (because first gt last)
  • unsuccessful search

39
  • Performance of Binary Search
  • Suppose that L is a sorted list of 1000 elements
  • Determine whether x is in L.

40
  • Suppose that x ? L499.
  • If x lt L499, the next iteration of the while
    loop looks for x in L0...L498 otherwise, the
    while loop looks for x in L500...L999.
  • Suppose that x lt L499. Then the next iteration
    of the while loop looks for x in L0...L498.

41
  • Suppose that x ? L249.
  • Suppose that x gt L249.
  • The next iteration of the while loop searches for
    x in L250...L498.

42
  • Every iteration of the while loop cuts the size
    of the search list in half.
  • 1000 ? 1024 210.
  • The while loop will have at most 11 iterations to
    determine whether x is in L.
  • Every iteration of the while loop makes 2 key
    (item) comparisons the binary search will make at
    most 22 key comparisons to determine whether x is
    in L.
  • Sequential search, on average, will make 500 key
    comparisons to determine whether x is in L.
  • Suppose that L is of size 1000000.
  • 1000000 ? 1048576 220
  • The while loop in the binary search will have at
    most 21 iterations to determine whether an
    element is in L.
  • To determine whether an element is in L, the
    binary search makes at most 42 key comparisons.
  • Sequential search will make 500,000 key (item)
    comparisons to determine whether an element is in
    L.

43
  • TWO- AND MULTIDIMENSIONAL ARRAYS

44
  • Two-dimensional Array A two-dimensional array is
    a collection of a fixed number of components
    arranged in two dimensions, and all components
    are of the same type.
  • The syntax for declaring a two-dimensional array
    is
  • dataType arrayNameintexp1intexp2
  • where intexp1 and intexp2 are expressions
    yielding positive integer values. The two
    expressions intexp1 and intexp2 specify the
    number of rows and the number of columns,
    respectively, in the array.
  • double sales105
  • declares a two-dimensional array sales of 10 rows
    and 5 columns and every component is of the type
    float.

45
(No Transcript)
46
  • Accessing Array Components
  • The syntax to access a component of a
    two-dimensional array is
  • arrayNameindexexp1indexexp2
  • where indexexp1 and indexexp2 are expressions
    yielding nonnegative integer values. indexexp1
    specifies the row position and indexexp2
    specifies the column position.
  • The statement
  • sales53 25.75
  • stores 25.75 into row numbered 5 and column
    numbered 3 (that is, 6th row and 4th column) of
    the array sales. If
  • int i 5
  • int j 3
  • then the previous statement is equivalent to
  • salesij 25.75

47
(No Transcript)
48
  • Two-Dimensional Array Initialization During
    Declaration
  • Like one-dimensional arrays, two-dimensional
    arrays can be initialized when they are declared.
  • int board43 2, 3, 1,
  • 15, 25, 13,
  • 20,4,7,
  • 11,18,14

49
  • To initialize a two-dimensional array when it is
    declared
  • 1. The elements of each row are enclosed within
    braces and separated by commas.
  • 2. All rows are enclosed within braces.
  • 3. For number arrays, if all components of a row
    are not specified, the unspecified components are
    initialized to zero.

50
  • Two-dimensional Arrays and Enumeration Types
  • We can also use enumeration type for array
    indices. Consider the following statements.
  • const int rows 6
  • const int colms 5
  • enum carTypeGM, Ford, Toyota, BMW, Nissan,
    Volvo
  • enum colorTypeRed, Brown, Black, White, Gray
  • int inStockrowscolms
  • inStock13 15
  • is equivalent to the statement
  • inStockFordWhite 15

51
(No Transcript)
52
(No Transcript)
53
  • Processing Two-dimensional Arrays
  • A two-dimensional array can be processed in three
    different ways.
  • 1. Process the entire array.
  • 2. Process a particular row of the array, called
    row processing.
  • 3. Process a particular column of the array,
    called column processing.

54
  • const int rows 7
  • const int columns 6
  • int matrixrowscolumns
  • int row
  • int col
  • int sum
  • int largest
  • int temp

55
(No Transcript)
56
  • Each row and each column of a two-dimensional
    array is a one-dimensional array.
  • When processing a particular row or column of a
    two-dimensional array we employ algorithms
    similar to process one-dimensional arrays.

57
  • Suppose that we want to process row number, say
    5 of matrix. The components of row number 5 of
    matrix are
  • matrix50, matrix51, matrix52,
  • matrix53, matrix54, matrix55

58
  • In these components the first index is fixed at
    5.
  • The second index ranges from 0 to 5.
  • The following for loop processes row number 5.
  • for(col 0 col lt columns col)
  • process matrix5col
  • This for loop is equivalent to the following for
    loop
  • row 5
  • for(col 0 col lt columns col)
  • process matrixrowcol

59
  • Similarly, suppose that we want to process
    column number 2 of matrix, that is, the third
    column of matrix. The components of this column
    are
  • matrix02, matrix12, matrix22,
  • matrix32, matrix42, matrix52,
  • matrix62

60
  • The second index is fixed at 2 and the first
    index ranges from 0 to 6.
  • The following for loop processes column 2 of
    matrix.
  • for(row 0 row lt rows row)
  • process matrixrow2
  • This for loop is equivalent to the following for
    loop
  • col 2
  • for(row 0 row lt rows row)
  • process matrixrowcol

61
  • Initialization
  • Suppose we want to initialize row number 4 to
    zero.
  • The following for loop initializes row four to
    zero.
  • row 4
  • for(col 0 col lt columns col)
  • matrixrowcol 0
  • To initialize the entire matrix to zero, we can
    also put the first index, that is, the row
    position in a loop.
  • The following nested for loops initialize each
    component of matrix to 0.
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • matrixrowcol 0

62
  • Print
  • The following nested for loops print the
    components of matrix, one row per line.
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • coutltltsetw(5)ltltmatrixrowcolltlt" "
  • coutltltendl

63
  • Input
  • The following for loop inputs data in row number
    4 of matrix.
  • row 4
  • for(col 0 col lt columns col)
  • cingtgtmatrixrowcol
  • By putting the row number in a loop we can input
    data in each component of the matrix.
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • cingtgtmatrixrowcol

64
  • Sum by Row
  • The following for loop finds the sum of row
    number 4 of matrix.
  • sum 0
  • row 4
  • for(col 0 col lt columns col)
  • sum sum matrixrowcol
  • By putting the row number in a loop we can find
    the sum of each row separately.
  • //Sum of each individual row
  • for(row 0 row lt rows row)
  • sum 0
  • for(col 0 col lt columns col)
  • sum sum matrixrowcol
  • coutltlt"Sum of row "ltltrow1ltlt" "
  • ltltsumltltendl

65
  • Sum by Column
  • //Sum of each individual column
  • for(col 0 col lt columns col)
  • sum 0
  • for(row 0 row lt rows row)
  • sum sum matrixrowcol
  • coutltlt"Sum of column "ltltcol1ltlt" "
  • ltltsumltltendl

66
  • Largest Element in Each Row and Each Column
  • The following for loop determines the largest
    element in row number 4.
  • row 4
  • largest matrixrow0
  • for(col 1 col lt columns col)
  • if(largest lt matrixrowcol)
  • largest matrixrowcol

67
  • //Largest element in each row
  • for(row 0 row lt rows row)
  • largest matrixrow0
  • for(col 1 col lt columns col)
  • if(largest lt matrixrowcol)
  • largest matrixrowcol
  • coutltlt"Largest element of row "ltltrow1
  • ltlt" "ltltlargestltltendl

68
  • //Largest element in each column
  • for(col 0 col lt columns col)
  • largest matrix0col
  • for(row 1 row lt rows row)
  • if(largest lt matrixrowcol)
  • largest matrixrowcol
  • coutltlt"Largest element of col "ltltcol1
  • ltlt" "ltltlargestltltendl

69
  • Reversing Diagonal
  • Suppose matrix is a square array, that is, the
    number of rows and the number of columns are the
    same.
  • Then matrix has a main diagonal and an opposite
    diagonal.
  • const int rows 4
  • const int columns 4
  • The components of the main diagonal of matrix
    are
  • matrix00, matrix11, matrix22, and
    matrix33.
  • The components of the opposite diagonal are
  • matrix03, matrix12, matrix21, and
    matrix30.

70
(No Transcript)
71
  • After reversing both the diagonals, the array
    matrix is

72
  • To reverse the main diagonal
  • 1. Swap matrix00 with matrix33, and
  • 2. Swap matrix11 with natrix22.
  • To reverse the opposite diagonal
  • 1. Swap matrix03 with matrix30, and
  • 2. Swap matrix12 with natrix21.

73
  • //Reverse main diagonal
  • for(row 0 row lt rows / 2 row)
  • temp matrixrowrow
  • matrixrowrow
  • matrixrows-1-rowrows-1-row
  • matrixrows-1-rowrows-1-row temp
  • //Reverse the opposite diagonal
  • for(row 0 row lt rows / 2 row)
  • temp matrixrowrows-1-row
  • matrixrowrows-1-row
  • matrixrows-1-rowrow
  • matrixrows-1-rowrow temp

74
  • Passing Two-dimensional Arrays as Parameters to
    Functions
  • Two-dimensional arrays can be passed as
    parameters to a function and they are passed by
    reference.
  • The base address, that is, the address of the
    first component of the actual parameter is passed
    to the formal parameter.
  • If matrix is the name of a two-dimensional array,
    then matrix00 is the first component of
    matrix.
  • When storing a two-dimensional array in the
    computers memory, C uses the row order form.
    That is, first the first row is stored, followed
    by the second row, which is followed by the third
    row and so on.
  • When declaring a two-dimensional array as a
    formal parameter, we can omit the size of the
    first dimension, but not the second, that is, the
    number of columns must be specified.

75
  • Consider the following function definition
  • void example(int table5, int rowsize)
  • .
  • .
  • .
  • This function takes as a parameter a
    two-dimensional array of unspecified number of
    rows, but 5 columns. During the function call the
    number of columns of the actual parameter must
    match the number of columns of the formal
    parameter.

76
  • Arrays of Strings
  • Arrays of Stings and the string Type
  • string list100
  • Arrays of Strings and C- Strings (Character
    Arrays)
  • char list10016

77
(No Transcript)
78
  • strcpy(list1, "Snow White")

for(j 0 j lt 100 j) coutltltlistjltltendl
79
  • Other form of Declaring Two-dimensional Arrays
  • const int numberOfRows 20
  • const int numberOfColumns 10
  • typedef int tableTypenumberOfRowsnumberOfColumn
    s
  • We can declare variables of the type tableType.
  • tableType matrix
  • void initialize(tableType table)
  • int row
  • int col
  • for(row 0 row lt numberOfRows row)
  • for(col 0 col lt numberOfColumns col)
  • tablerowcol 0

80
  • Multi-dimensional Arrays
  • Array An array is a collection of a fixed number
    of elements (called components) arranged in n
    dimensions (n gt 1), called an n-dimensional
    array.
  • The general syntax of declaring an n-dimensional
    array is
  • dataType arrayNameintExp1intExp2...intExpn
  • where intExp1, intExp2, , and intExpn are
    constant expressions yielding positive integer
    values.

81
  • The syntax of accessing a component of an
    n-dimensional array is
  • arrayNameindexExp1indexExp2...indexExpn
  • where indexExp1,indexExp2,..., and indexExpn are
    expressions yielding nonnegative integer values.
    indexExpi gives the position of the array
    component in the ith dimension.

82
  • The statement
  • double carDealers1057
  • declares carDealers to be a three-dimensional
    array.
  • Size of the first dimension is 10 and it ranges
    from 0 to 9.
  • The size of the second dimension is 5 and it
    ranges from 0 to 4.
  • The size of the third dimension is 7 and it
    ranges from 0 to 6.
  • The base address of the array carDealers is the
    address of the first array component, that is the
    address of carDealers000.
  • The total number of components in the array
    carDealers is 1057 350.

83
  • carDealers532 15564.75
  • for(i 0 i lt 10 i)
  • for(j 0 j lt 5 j)
  • for(k 0 k lt 7 k)
  • carDealersijk 0.0
  • initializes the entire array to 0.0.

84
  • When declaring a multi-dimensional array as a
    formal parameter in a function, we can omit the
    size of the first dimension but not the other
    dimensions.
  • As parameters multi-dimensional arrays are passed
    by reference only and a function cannot return a
    value of the type array.
  • There is no check if the array indices are within
    bounds.

85
  • PROGRAMMING EXAMPLE ELECTION RESULTS
  • The presidential election for the student council
    of your local university will be held soon. For
    reasons related to confidentiality, the chair of
    the election committee wants to computerize the
    voting. The chair is looking for someone to write
    a program to analyze the data and report the
    winner. Let us to write a program to help the
    election committee.
  • The university has four major divisions and each
    division has several departments. For the purpose
    of the election, the four divisions, are labeled
    as Region 1, Region 2, Region 3, and Region 4.
    Each department in each division manages its own
    voting process and directly reports the votes
    received by each candidate to the election
    committee. The voting is reported in the
    following form
  • candidate_name region number_of_votes_for_this_ca
    ndidate

86
  • The election committee wants the output in the
    following tabular form.
  • --------------Election Results-------------
    -
  • Candidate Votes
  • Name Region1 Region2 Region3 Region4
    Total
  • --------- ------- ------- ------- -------
    ------
  • Balto 0 0 0 272
    272
  • Doc 25 71 156 97
    349
  • .
  • .
  • .
  • Winner ???, Votes Received ???
  • Total votes polled ???
  • The names of the candidates in the output must
    be in alphabetical order.
  • For this program we assume that there are six
    candidates seeking student councils president
    post.

87
  • The data is provided in two files. One file, say
    candDat.txt consist the names of candidates
    seeking the presidents post. The names of the
    candidates in the file are in no particular
    order. In the second file each line consists of
    voting results in the following form
  • candidateName regionNumber numberOfVotesForThisCan
    didate
  • For example, the input file looks like
  • Donald 1 23
  • Pluto 2 56
  • Doc 1 25
  • Pluto 4 23
  • .
  • .
  • .
  • The first line indicates that Donald received 23
    votes from region 1.

88
  • Input Two files, one containing candidates name
    and the other containing the votes data as
    described above.
  • Output Election results in a tabular form as
    described above and the winner.

89
  • Problem Analysis and Algorithm Design
  • The program must organize the voting data by
    region.
  • The program must also calculate the total number
    of votes received by each candidate as well as
    the total votes cast in the election.
  • The names of the candidates must appear in
    alphabetical order.
  • The data type of a candidates name (which is a
    string) and the data type of the number of votes
    (which is an integer) are different, we need two
    separate arraysone to hold the candidates names
    and one to hold the voting data.
  • The array to hold the names of the candidates is
    a one-dimensional array, and each component of
    this array is a string.
  • Instead of using a single two-dimensional array
    to hold the voting data, we will 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.

90
(No Transcript)
91

1. Read the candidates names into the array
candidatesName. 2. Sort the array
candidatesName. 3. Initialize the arrays
votesByRegion and totalVotes. 4. Process the
voting data. 5. Calculate the total votes
received by each candidate. 6. Output the
results.
92
  • Function getCandidatesName
  • void getCandidatesName(ifstream inp,
  • string cNames, int
    noOfRows)
  • int i
  • for(i 0 i lt noOfRows i)
  • inpgtgtcNamesi //read candidate_name
  • After a call to this function, the arrays to hold
    the data are

93
(No Transcript)
94
  • Function sortCandidatesName
  • This function uses selection sort algorithm (As
    discussed in this chapter) to sort the array
    candiatesName.
  • void sortCandidatesName(string cNames,
  • int noOfRows)
  • int i, j
  • int min
  • //selection sort
  • for(i 0 i lt noOfRows - 1 i)
  • min i
  • for(j i 1 j lt noOfRows j)
  • if(cNamesj lt cNamesmin)
  • min j
  • cNamesi.swap(cNamesmin)

95
(No Transcript)
96
  • Function initialize

97
  • void initialize(int vbRegionnoOfRegions,
  • int tVotes, int noOfRows)
  • int i,j
  • for(i 0 i lt noOfRows i)
  • for(j 0 j lt noOfRegions j)
  • vbRegionij 0
  • for(i 0 i lt noOfRows i)
  • tVotesi 0

98
  • Process Voting Data
  • For each entry in the file voteDat.txt, we do the
    following
  • 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.
  • 3. Find the column in the array votesByRegion
    corresponding to the regionNumber.
  • 4. Update the appropriate entry in the array
    votesByRegion by adding numberOfVotesForTheCandida
    te.

99
Suppose that the three arrays are
  • Suppose that the next entry read from the input
    file is
  • Donald 2 35

100
  • We locate the row in the above grid that
    corresponds to this candidate.
  • To find the row, we search the array
    candidatesName to find the row that corresponds
    to this name.
  • Donald corresponds to row number 2 in the array
    candidatesName.

101
  • votesByRegion21 votesByRegion21 35

102
  • Function binSearch
  • int binSearch(string cNames, int noOfRows,
    string name)
  • int first, last, mid
  • bool found
  • first 0
  • last noOfRows - 1
  • found false
  • while(!found first lt last)
  • mid (first last) / 2
  • if(cNamesmid name)
  • found true
  • else
  • if(cNamesmid gt name)
  • last mid - 1

103
  • Function processVotes
  • void processVotes(ifstream inp, string cNames,
  • int vbRegionnoOfRegions, int noOfRows)
  • string candName
  • int region
  • int noOfVotes
  • int loc
  • inpgtgtcandNamegtgtregiongtgtnoOfVotes //Step a
  • while(inp)
  • loc binSearch(cNames,noOfRows,candName)
    //Step b
  • if(loc ! -1)
  • vbRegionlocregion - 1
  • vbRegionlocregion - 1
  • noOfVotes //Steps c and d
  • inpgtgtcandNamegtgtregiongtgtnoOfVotes //Step
    a

104
  • Calculate Total Votes (Function addRegionsVote)

105
(No Transcript)
106
  • void addRegionsVote(int vbRegionnoOfRegions,
  • int tVotes, int noOfRows)
  • int i,j
  • for(i 0 i lt noOfRows i )
  • for(j 0 j lt noOfRegions j)
  • tVotesi tVotesi vbRegionij

107
  • Function printHeading
  • void printHeading()
  • coutltlt" --------------Election
    Results--------------"
  • ltltendlltltendl
  • coutltlt"Candidate Votes"ltltendl
  • coutltlt"Name Region1 Region2 Region3
    "
  • ltlt"Region4 Total"ltltendl
  • coutltlt"--------- ------- ------- -------
    ------- "
  • ltlt"------"ltltendl

108
  • Function printResults
  • i. Initialize, sumVotes, largestVotes, and winLoc
    to 0.
  • ii. For each row in each array
  • a. if (largestVotes lt tVotesi)
  • largestVotes tVotesi
  • winLoc i
  • b. sumVotes sumVotes tVotesi
  • c. Output data from corresponding rows of each
    array.
  • iii. Output the final lines of output.

109
  • void printResults(string cNames, int
    vbRegionnoOfRegions,
  • int tVotes, int noOfRows)
  • int i, j
  • int largestVotes 0 //Step i
  • int winLoc 0 //Step i
  • int sumVotes 0 //Step i
  • for(i 0 i lt noOfRows i) //Step ii
  • if(largestVotes lt tVotesi) //Step ii.a
  • largestVotes tVotesi
  • winLoc i
  • sumVotes sumVotes tVotesi //Step ii.b
  • //Step ii.c

110
  • for(j 0 j lt noOfRegions j)
  • coutltltsetw(8)ltltvbRegionijltlt" "
  • coutltltsetw(6)ltlttVotesiltltendl
  • //step iii
  • coutltltendlltltendlltlt"Winner "ltltcNameswinLoc
  • ltlt", Votes Received "ltlttVoteswinLocltltendl
  • ltltendl
  • coutltlt"Total votes polled "ltltsumVotesltltendl

111
  • Main Algorithm Function main
  • 1. Declare the variables
  • 2. Open the input file candDat.txt.
  • 3. If the input file does not exist, exit the
    program.
  • 4. Read the data from the file candData.txt into
    the array candidatesName.
  • 5. Sort the array candidatesName.
  • 6. Close the file candDat.txt
  • 7. Open the input file voteDat.txt.
  • 8. If the input file does not exist, exit the
    program
  • 9. Initialize the arrays, votesByRegion and
    totalVotes.
  • 10. Process the voting data and store the results
    in the array votesByRegion.

112
  • 11. Calculate the number of total votes received
    by each candidate and store the results in the
    array totalVotes.
  • 12. Print the heading.
  • 13. Print the results.

113
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltstringgt
  • include ltiomanipgt
  • using namespace std
  • const int noOfCandidates 6
  • const int noOfRegions 4
  • void printHeading()
  • void initialize(int vbRegionnoOfRegions,
  • int tVotes, int noOfRows)
  • void getCandidatesName(ifstream inp,
  • string cNames, int noOfRows)
  • void sortCandidatesName(string cNames, int
    noOfRows)
  • int binSearch(string cNames, int noOfRows,
  • string name)
  • void processVotes(ifstream inp, string cNames,

114
  • int main()
  • //Declare variables Step 1
  • string candidatesNamenoOfCandidates
  • int votesByRegionnoOfCandidatesnoOfRegions
  • int totalVotesnoOfCandidates
  • ifstream infile
  • infile.open("acandData.txt") //Step 2
  • if(!infile) //Step 3
  • coutltlt"Input file (candData.txt) does not
    exit."
  • ltltendl
  • return 1
  • getCandidatesName(infile, candidatesName,
  • noOfCandidates) //Step 4
  • sortCandidatesName(candidatesName,noOfCandidate
    s) //Step 5

115
  • if(!infile) //Step 8
  • coutltlt"Input file (voteData.txt) does not
    exit."
  • ltltendl
  • return 1
  • initialize(votesByRegion, totalVotes,
    noOfCandidates) //Step 9
  • processVotes(infile, candidatesName,
    votesByRegion,
  • noOfCandidates) //Step 10
  • addRegionsVote(votesByRegion, totalVotes,
  • noOfCandidates) //Step 11
  • printHeading() //Step 12
  • printResults(candidatesName,votesByRegion,
  • totalVotes,noOfCandidates)
    //Step 13
  • return 0

116
  • Definitions of remaining functions, discussed
    above and specified in the function prototypes,
    goes here.

117
  • Sample Run
  • --------------Election Results--------------
  • Candidate Votes
  • Name Region1 Region2 Region3 Region4
    Total
  • --------- ------- ------- ------- -------
    ------
  • Balto 0 0 0 272
    272
  • Doc 25 71 156 97
    349
  • Donald 110 158 0 0
    268
  • Goofy 0 34 0 0
    34
  • Mickey 112 141 156 89
    498
  • Pluto 285 56 0 46
    387
  • Winner Mickey, Votes Received 498
  • Total votes polled 1808
Write a Comment
User Comments (0)
About PowerShow.com