2nd Midterm Exam - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

2nd Midterm Exam

Description:

Title: Designing Classes and Programs Author: Owen Astrachan Last modified by: Albert Levi Created Date: 9/7/1997 11:16:48 PM Document presentation format – PowerPoint PPT presentation

Number of Views:108
Avg rating:3.0/5.0
Slides: 59
Provided by: Owen109
Category:

less

Transcript and Presenter's Notes

Title: 2nd Midterm Exam


1
2nd Midterm Exam
  • December 5th, 2015, Saturday
  • 1000 1200
  • Places are below (according to last name)
  • FASS G022 Açilan Baris
  • FASS G049 Basdal Çelik
  • FASS G052 Çetin Erdurgut
  • FASS G056 Eren Gez
  • FENS L045 Ghanem Kolasin
  • FASS G062 Korkmaz Sertbas
  • FENS G077 Sevim - Zor
  • Sample question set and solutions are posted
  • Close everything except two A4-size cheat notes
  • In the final exam, two sheet limit wont change!
  • Exam covers the topics until the beginning of
    structs and vectors!
  • Details are announced at SUCourse and are sent as
    an email to the class email list.

2
Extra Recitations for Review Purposes
  • by Emir Artar
  • Several recitations will be held until MT2
  • First Meeting to determine the coverage and time
  • Wednesday November 25, 1940 in FASS G022
  • Exact times will be determined in this first
    meeting
  • Actually these have been done in previous week.
    Please follow emails by me or Emir about the
    extra recitation time slots.

3
Announcements about HW6
  • You may need to use clear() member function
    before you try to reopen an input file stream
    object
  • (i) that you failed to open previously (for
    example due to wrong file name), or
  • (ii) (may not be the case for this homework) that
    you opened and processed but for some reason if
    the error flags are set (for example due to
    reaching the end of the file).
  • Possible reasons for run time errors in this
    homework
  • Attempting to read from a file that has not been
    opened yet
  • Attempting to write to a file that has not been
    opened yet
  • Range and index problems while trying to access
    characters of a string using find, substr and at
    member functions.

4
Announcements about HW6
  • Should we check if the output file is opened
    successfully or not?
  • Not required, but advised. There might be some
    cases that the output files are not opened
    successfully
  • If you check and the output file is not opened,
    then do not continue with the program.
  • What happens if the files are opened but the
    content is irrelevant? Should we make the content
    check for the files that are opened successfully?
  • NO. As mentioned in the HW document, the content
    of the files are assumed to be correct. What you
    have to do is only to check if the files are
    opened successfully or not and continue to read
    file names until opened. Once opened, we assume
    that the file is the required database file.
  • Some of you check whether the input file name is
    "data.txt" as the input file check at the
    beginning of the program
  • This is nonsense the input file name can be
    anything data.txt is just an example it could
    also be cimbom.bom, enbuyuk.gs, or any other
    name.
  • What you will do is to open the file with the
    entered input file name and check whether it is
    opened successfully or not. If so OK, if not
    continue by reading another file name and try to
    open it until the file is successfully opened.

5
7th and last homework
  • 7th and last homework will be assigned this week
  • Due December 16 Wednesday, 1900
  • About vectors
  • This week recitations will be about vectors and
    this homework

6
Whats Left in the Course
  • Structs (from Chapter 7.4), Arrays and vectors
    (Chapter 8)
  • including searching and sorting (partially
    Chapter 11)
  • Recursion, scope rules, global and static
    variables
  • partially Chapter 10
  • These are not included in the second midterm exam

7
structs (Chapter 7.4)
  • Used as data aggregates for an entity
  • can be different types of data
  • e.g. for student
  • id, name, GPA, address, ...
  • Similar to classes, but everything is public
  • structs can have constructors
  • structs can have member functions
  • we will not deal with constructors and member
    functions for structs unless they are necessary
  • mostly we will use structs for combining data for
    an entity into a single structure

8
Structs
  • Example struct for student
  • First struct must be defined by giving it a name
    and its fields (data)
  • struct student // student is struct
    name
  • unsigned int id //fields of student
    struct
  • string name, lastname
  • double gpa
  • // dont forget at the
    end
  • Then variables of that type are declared and
    used.
  • dot operator is used to refer fields of a struct
    variable
  • student stu
  • stu.name "Ali"
  • stu.gpa 4.0
  • cout ltlt stu.gpa
  • See structdemo.cpp (not in book)

stu
gpa
id
4.0
name
Ali
lastname
9
What can and cant be done with structs
  • Structs can be passed to functions as parameters
  • use const-reference if not changing (using value
    parameter is syntactically OK, but not preferred
    due to performance reasons)
  • use reference parameter if changing
  • struct fields behave as variables/objects of
    field type
  • id is an integer
  • name is a string
  • You may read, write, use as operands in
    operations, etc.
  • However, processing the entire struct variable is
    restrictive
  • cannot read or write (using gtgt and ltlt) structs
    unless those operators are specially defined for
    that struct
  • cannot use operators (except assignment) between
    two structs unless those operators are specially
    defined for that struct
  • see 7.4.2 for operator definitions for structs,
    but you are not responsible
  • Assignment operator works properly (fields are
    copied)
  • structs are useful mostly in vectors (arrays) as
    we shall see

10
Vectors and Arrays
  • Arrays are collections of several elements of the
    same type
  • E.g. 100 integers, 20 strings, 125 students, 12
    dates, etc.
  • Single name is given to the entire array
  • But each element is accessed separately
  • Any element of an array can be accessed just as
    quickly as any other element (this is called
    random access but do not get confused with
    RandGen type of randomness)
  • In C/C there is a built-in array type
  • We will see it, but later
  • Vectors are a class-based version of arrays
  • First we will see vectors.

11
Vectors
  • Vectors are a class-based version of arrays
  • Were using the standard C class called vector
  • At the beginning of the program you have to have
    include ltvectorgt
  • No cpp necessary since it is a standard class
  • There are several member functions of the vector
    class that make our life easier.
  • We will see them later
  • But first we will a motivating example and some
    basics

12
Why do we need arrays/vectors?
  • Consider the following example (not in the book)
  • pick n random numbers between 0 and 6 and count
    total number of occurrences of all outcomes (0,
    1, 2, 3, 4, 5, 6)
  • n is an input
  • we need 7 counters
  • 7 declarations
  • 7 initializations
  • 7 conditions to increment after each occurrence
  • 7 cout statements to display the result
  • Fortunately, we have shorter way ARRAYS/VECTORS
  • We can use vectors to store counters for all
    possible outcomes of the random numbers under a
    single name
  • easier processing in loops
  • see next slide for the program

13
Example
  • Previous example using vectors - see randnums.cpp
  • int num
  • int k
  • RandGen random
  • vectorltintgt randStats(7) // vector for counters
  • int n PromptRange("how many random
    numbers",1,20000)
  •  
  • for(k0 k lt 6 k) // initialize
    counters to zero
  • randStatsk 0
  •  
  • for(k0 k lt n k) // pick all random
    numbers
  • num random.RandInt(7) // between 0 and 6
  • randStatsnum randStatsnum 1 // and
    increment
  • //
    corresponding counter
  •  
  • cout ltlt "number\t\t of occurrences" ltlt endl

14
Vector/Array basics
  • Vectors/Arrays are homogeneous
  • each item (sometimes called element) has the same
    type
  • this type must be specified at declaration
  • Items in a vector/array are numbered (e.g. 1st,
    3rd, or 105th)
  • those are called index or subscript
  • numbering starts with 0
  • we have to use the index value to refer an
    element in a vector/array
  • Example definition and use of vectors (array
    definition is a bit different will see later)
  • vectorltintgt ivals(10) // ivals can store 10
    ints
  • ivals0 3 // 0th element
    becomes 3
  • vectorltstringgt svals(20) // svals can store 20
    strings
  • svals4 "cs201" // 4th element
    contains "cs201"

15
Vector basics
  • Syntax of vector declaration
  • vector is a class, its declaration is
    construction
  • 3 different methods
  • vectorlttypegt variable_name
  • empty vector (will see later)
  • vectorlttypegt variable_name (size_expression)
  • vector with size_expression elements in it
  • vectorlttypegt variable_name (size_expression,
    init_value)
  • vector with all size_expression elements, all
    initialized to init_value

16
Vector basics
  • size_expression can be any expression of type
    integer (or cast into integer)
  • not necessarily a constant value (this is
    actually a very important flexibility as compared
    to built-in arrays)
  • examples
  • vector ltintgt letters (int('Z')-int('A') 1)
  • creates a vector of 26 integer elements and name
    it letters
  • cin gtgt num
  • vector ltdoublegt counters (num)
  • creates a vector of doubles total number of
    elements is input
  • Index values start with 0, and end with size-1
  • type is type of the vector elements
  • can be built-in types (int, double, ...) or user
    defined types or classes or structs (string and
    date are class examples student is struct
    example)
  • classes must have default constructors to be used
    in vector definition as element type

17
Defining vector objects
  • Can specify elements in a vector, optionally an
    initial value
  • vectorltintgt counts(300) // 300 ints,
    values not initialized
  • vectorltintgt nums(200,0) // 200 ints, all
    zero
  • vectorltdoublegt d(10,3.14) // 10 doubles, all
    pi
  • vectorltstringgt w(10,"cs")// 10 strings, all
    "cs"
  • vectorltstringgt words(10) // 10 strings, all
    ""
  • If the vector type is a class, then this class
    must have a default constructor
  • Default constructor is the one without parameters
  • Cannot define vectorltDicegt cubes(10) since Dice
    doesnt have default constructor
  • Vectors of classes are initialized with the
    default constructor
  • that is why all words are "" (empty string)
  • Default constructor of the string class generates
    an empty string
  • Vectors of built-in types are not initialized
    (unless explicitly initialized with the second
    argument of vector definition)

18
Example vector definitions
  • vectorltintgt counter(9, 0)
  • each element is an integer(all initialized to 0)

0 0 0 0 0 0 0 0 0
vectorltchargt letters(18) each element is a char
(not initialized yet)
9 10 11 12 13 14 15 16 17
vectorltDategt holidays(6) each element is a date
object that contains todays date
holidays
24 11 2015
24 11 2015
24 11 2015
24 11 2015
24 11 2015
24 11 2015
0 1 2 3 4 5
19
How to reach a single vector/array element
  • specify the index value within square brackets
    after the vector/array name
  • var_name index_expr
  • the value of index expression must be between 0
    and vector size - 1
  • Examples
  • vectorltintgt nums(9)
  • nums5 102
  • nums0 nums52-1
  • numsnums5/20-3 55
  • nums10 5 // error

nums
203
55
102
20
Passing vectors to functions as parameters
  • Vectors can be passed as parameters to functions
  • Pass by reference (if function changes the
    vector)
  • void Count (vectorltintgt counts)
  • Pass by const-reference (if no changes made).
  • void Print(const vectorltintgt counts)
  • Passing by value makes a copy, requires time and
    space, so not preferred
  • IMPORTANT!!! vector size cannot be given in
    parameter definition. Three solutions to this
    problem
  • the size may be passed as another parameter
  • the size may be fixed and known
  • vector class has a member function, size, to
    return the size of a vector (shall see later)

21
Example
  • Counting letters of a file
  • display number of occurrences of each letter at
    the end
  • counting is case insensitive
  • see letters.cpp (the one in book is a bit
    different)

22
vector as a return type
  • Vector can be return type of a function
  • vectorltintgt Count (istream input, int
    total)
  • Example modify letters.cpp such that count
    returns the vector (not as reference parameter)
  • see letters2.cpp

23
Vectors of structs
class
0
  • We can define vectors of structs
  • struct student
  • unsigned int id
  • string name, lastname
  • double gpa
  • vectorltstudentgt class(11)
  • // a vector with 11 students
  • class1.gpa 3.2
  • for (i 0 i lt 10 i)
  • classi.id i 1250

1
10
24
Vector of struct
  • Example
  • define a struct for a track on a CD
  • track number and title are fields
  • define a vector for 10 tracks
  • shuffle these 10 tracks at random
  • see shuffle.cpp (in book, but this version is
    slightly modified)

25
Vectors as lists
  • The vector as counters example constructs and
    initializes a vector with a specific number of
    elements
  • Other uses of vector require the vector to grow
    to accommodate new elements
  • Consider reading words from a text file, storing
    them in a vector
  • How big should we define vector initially? What
    are potential problems?
  • When a vector is used as a list, well use a
    different method for adding elements to the
    vector so that the vector can grow

26
Reading words into a vector (problematic version)
  • vectorltstringgt words(1000)
  • string w
  • int i 0
  • string filename PromptString("enter file name
    ")
  • ifstream input(filename.c_str())
  • while (input gtgt w)
  • wordsiw
  • i
  • cout ltlt "read " ltlt i ltlt " words" ltlt endl
  • What is the problem?
  • there might be more than 1000 words in the file
  • in this case, index runs out of range

27
Reading words into a vector (with index range
control but still problematic)
  • vectorltstringgt words(1000)
  • string w
  • int i 0
  • string filename PromptString("enter file name
    ")
  • ifstream input(filename.c_str())
  • while ((input gtgt w) (i lt 1000))
  • wordsiw
  • i
  • cout ltlt "read " ltlt i ltlt " words" ltlt endl
  • What is the problem?
  • works fine if there are no more than 1000 words
  • but if there are more than 1000 words, the rest
    is not read

28
Reading words into a vector (no problems)
  • One method would be to pass over the file two
    times
  • one to find out number of words
  • second to read the words into array
  • Another method is to benefit from vector class
    utilities (member functions) as in the following
    code
  • vectorltstringgt words //create empty vector
  • string w
  • string filename PromptString("enter file name
    ")
  • ifstream input(filename.c_str())
  • while (input gtgt w)
  • words.push_back(w) //adds the next word to the
    vector
  • //also increases the size if necessary
  • cout ltlt "read " ltlt words.size() ltlt " words" ltlt
    endl

29
Using vectorpush_back
  • The method push_back adds new objects to the
    end of a vector,
  • Internally, the vector keeps track of its
    capacity
  • If there is capacity, then there is no problem
    the new item is added to the end of the vector
  • When the capacity is reached (i.e. if there is no
    capacity) and push_back attempts to add a new
    element to the vector, then the vector
    automatically grows by adding half of the
    current capacity to the current capacity
  • 0, 1, 2, 3, 4, 6, 9, 13, 19, 28, 42, ... n n/2
  • Rule is adding the half of the existing capacity
    (by rounding down except the first three
    elements of the list)
  • The book explains this increase in a different
    way since the book uses a different vector class
    please know the one I explained here
  • The case above happens when applying push_back
    mechanism to an initially empty vector defined
    without specifying a size
  • Initially size and capacity are zero
  • Other cases (initially non-empty vectors and
    adding capacity with some mechanisms) will be
    seen in a moment

30
Size versus Capacity
  • Capacity is the allocated memory (in terms of
    number of elements to be stored) of the vector
  • Size is how many elements are in the vector so
    far
  • They are not the same concepts, but related as
    described in the previous slide and illustrated
    below
  • vectorltstringgt names // size is 0, capacity
    is 0
  • names.push_back("Ali") // size is 1, capacity
    is 1
  • names.push_back("Husnu") // size is 2, capacity
    is 2
  • names.push_back("Ayse") // size is 3, capacity
    is 3
  • names.push_back("Cem") // size is 4, capacity
    is 4
  • names.push_back("Jale") // size is 5, capacity
    is 6
  • names.push_back("Hale") // size is 6, capacity
    is 6
  • names.push_back("Veli") // size is 7, capacity
    is 9
  • names.push_back("Gonca") // size is 8, capacity
    is 9
  • names.push_back("Fatma") // size is 9, capacity
    is 9
  • names.push_back("Yesim") //size is 10, capacity
    is 13

31
size()member function
  • size() member function basically returns the
    number of elements in the vector
  • When a vector is defined with no initial
    capacity, and push_back is used to add elements,
    size() member function returns the number of
    elements exist in the vector
  • This is the number of calls of push_back() if no
    elements are deleted
  • If elements deleted using pop_back(), size
    updated too (decremented)
  • If a non-empty vector is created, then the
    capacity and the size is set to the number of
    elements of the vector. This capacity is
    considered full, so the first push_back increases
    the capacity by adding half of the current
    capacity to the current capacity.
  • What about size() in case the vector is created
    as a non-empty one
  • returns the size specified during declaration if
    no push_back() is used
  • returns the size specified during declaration
    the number push_back()s, if push_back() is used

32
capacity() reserve() pop_back()
  • The capacity of vector is accessible using
    capacity()member function
  • programmers normally do not need this value
  • An initial capacity of N elements can be
    specified using reserve(N) member function
  • Normally used after creating an empty vector.
  • Reserves capacity, but the reserved capacity is
    not considered full (as opposed to creating a
    vector by specifying the size).
  • The last element of the vector can be deleted
    using pop_back() member function
  • Size is decremented by one
  • Capacity does not change
  • The deleted value is not returned

33
Demo Example
  • Read some strings from keyboard and store in a
    vector of strings. At the end display the vector.
  • version 1 no reserve
  • version 2 (decomment the reserve lines) with
    reserve
  • version 3 vector is created as a non-empty
    (decomment second definition and comment out
    first one and reserve lines)
  • You can also see an example use of pop_back()
  • See vectordemo.cpp (not in the book)

34
Vector Processing Examples 1 (vectorproc.cpp
not in book)
  • write a function that takes a vector of integers
    as parameter and returns the maximum of numbers
    in it
  • process all array elements for loop from 0 to
    vectors size - 1

int max (const vectorltintgt v) //pre vector v
is not empty //post return max of elements in
v int i, max_so_far INT_MIN for (i0 i lt
v.size() i) if (vi gt max_so_far)
max_so_far vi return max_so_far
35
Vector Processing Examples 2 (vectorproc.cpp
not in book)
  • write a function that takes a vector of integers
    as parameter and returns true if the vector is
    sorted in ascending manner, false otherwise
  • may not process all vector elements
  • In this type of rule-checking applications, a
    possible method is to assume that the rule is
    satisfied before the loop and find a
    counterexample in the loop

bool issorted (const vectorltintgt v) //post
returns true if the array is acsending sorted
bool s true // initially assume that
array is sorted //in the function try
to break this assumption int i 1 while (i lt
v.size() s true) //check until
the end of array or until a counterexample is
found if (vi-1 gt vi) // if not
sorted s false //
counterexample is found i return s
36
Searching a vector
  • We can search for one occurrence, return
    true/false or the index of occurrence
  • Search the vector starting from the beginning
  • Stop searching when match is found or when the
    end of the vector is reached
  • We can search and count the total number of
    occurrences and return count
  • Search entire vector
  • Similar to one occurrence search, but do not stop
    after first occurrence
  • We can search for many occurrences, but return
    occurrences in another vector rather than
    returning count
  • In all these cases, we search the vector
    sequentially starting from the beginning
  • This type of search is called sequential search

37
Counting search (sequential)
  • int countmatches(const vectorltstringgt a, const
    string s)
  • // post returns occurrences of s in a
  • int count 0
  • int k
  • for(k0 k lt a.size() k)
  • if (ak s)
  • count
  • return count
  • How can we change this code to return the index
    of the first occurrence?
  • see next slide

38
One occurrence search (sequential)
  • int firstmatch(const vectorltstringgt a, const
    string s)
  • // post returns the index of occurrence of s in
    a, -1
  • // otherwise
  • int k
  • for(k0 k lt a.size() k)
  • if (ak s)
  • return k
  • return -1
  • Does not search the entire array if one match is
    found
  • good for efficiency purposes
  • How could you modify this to return true/false?

39
Collecting search (sequential)
  • Collect the occurrences in another vector
  • void collect(const vectorltstringgt source,
  • vectorltstringgt matches)
  • // pre matches is empty
  • // post matches contains all elements of source
    with
  • // first letter 'A'
  • int k
  • for(k0 k lt source.size() k)
  • if (sourcek.substr(0,1) "A")
  • matches.push_back(sourcek)

40
Binary search
  • Alternative to sequential search for sorted
    vectors
  • If a vector is sorted, we can use the sorted
    property to eliminate half of the vector elements
    with one comparison
  • Consider the number guessing game. Which number
    (between 1 and 100) do we guess first in number
    guessing game?
  • Apply the same idea for searching in the sorted
    vector
  • Idea of creating program to do binary search
  • Check the middle element
  • If it has the searched value, then youre done!
  • If not, eliminate half of the elements of the
    vector using sortedness property of the vector
  • search the rest using the same idea
  • continue until match is found or there is no
    match
  • how could you understand that there is no match?
  • lets develop the algorithm on an example
  • we need two index values, low and high, for the
    search space

41
Binary Search (search for 62)
0 1 2 3 4 5 6 7 8 9 10 11 12
13 14
10 24 34 52 55 62 67 75 80 81
90 92 100 101 111
Low0 mid7
high14
Low0 mid3 high6
Low4 high6
mid5 gt FOUND
42
Binary Search (search for 60)
0 1 2 3 4 5 6 7 8 9 10 11 12
13 14
10 24 34 52 55 62 67 75 80 81
90 92 100 101 111
Low0 mid7
high14
Low0 mid3 high6
Low4 high6
mid5
Low4 high4
mid4
Low5 high4 gt NO MATCH FOUND STOP
43
Binary search code
  • int bsearch(const vectorltstringgt list, const
    string key)
  • // pre list.size() elements in list
  • // post returns index of key in list, -1 if key
    not found
  • int low 0 // leftmost
    possible entry
  • int high list.size()-1 // rightmost
    possible entry
  • int mid // middle of
    current range
  • while (low lt high)
  • mid (low high)/2
  • if (listmid key) // found key,
    exit search
  • return mid
  • else if (listmid lt key) // key in
    upper half
  • low mid 1
  • else // key in
    lower half
  • high mid - 1

44
Comparing Sequential and Binary Search
  • Given a list of N elements
  • Binary search makes on the order of log2N
    operation
  • O(log2N)
  • Linear (sequential) search takes on the order of
    N operations
  • O(N)

45
More vector processing insertion and deletion
  • Its easy to insert at the end of a vector, just
    use push_back()
  • However, if the vector is sorted and if we want
    to keep it sorted, then we cant just add to the
    end.
  • We have to find an appropriate position to insert
    the element and do some shifts.
  • If we need to delete an element from a sorted
    vector, how can we close-up the hole created by
    the deletion?
  • Shift elements left by one index, and decrease
    the size
  • we decrease size using pop_back()
  • pop_back() changes size, not capacity

46
Inserting an element into a sorted vector
Example
2 7 11 18 21 22 26 89 99
  • Insert NewNum which is e.g. 23
  • Is the vector capacity sufficient for an
    extra element?
  • You should make sure that there is capacity for
    insertion
  • What would you do to insert 23 in the right
    spot?

47
Insertion into sorted vector
0 1 2 3 4 5 6 7 8
2 7 11 18 21 22 26 89 99
NewNum 23
2 7 11 18 21 22 26 26 89 99
0 1 2 3 4 5 6 7 8 9
48
Insert into sorted vector
  • void insert(vectorltintgt a, int newnum) // NOT
    const vector
  • // pre a0 lt lt aa.size()-1, a is sorted
  • // post newnum inserted into a, a still sorted
  • int count a.size() //size before insertion
  • a.push_back(newnum) //increase size
    newnum is inserted at
  • //the end but the inserted
    value is not important
  • int loc count // start searching
    insertion location from end
  • while (loc gt 0 aloc-1 gt newnum)
  • aloc aloc-1
  • loc-- // shift right until the
    proper insertion cell
  • aloc newnum //actual insertion
  • See vectorproc.cpp (not in book)

49
What about deletion?
  • Remove the element at a given position (pos)
  • void remove(vectorltstringgt a, int pos)
  • // post original apos removed, size decreased
  • int lastIndex a.size()-1
  • apos alastIndex
  • a.pop_back()
  • What about if vector is sorted, what changes?
  • Whats the purpose of the pop_back() call?

50
Deletion from sorted vector
Ex Delete element at position 3
Size is 9
0 1 2 3 4 5 6 7 8
2 7 11 18 21 22 26 89 99
First shift all elements on the right of 3rd
element one cell to the left
0 1 2 3 4 5 6 7 8
2 7 11 21 22 26 89 99 99
pop back the last element of vector
0 1 2 3 4 5 6 7
2 7 11 21 22 26 89 99 99
Size is now 8
51
Deletion from sorted vector
  • void remove(vectorltintgt a, int pos)
  • // pre a is sorted
  • // post original apos removed, a is still
    sorted
  • int lastIndex a.size()-1
  • int k
  • for(kpos k lt lastIndex k)
  • ak ak1
  • //shift all elements on the right of pos
    one cell left
  • a.pop_back() //remove the last element of the
    array
  • Does pop_back() actually remove an element?
  • no, it just decreases the size so that the last
    element becomes unreachable
  • capacity remains the same
  • See vectorproc.cpp (not in book)

52
Sorting
  • One of the fundamental operations in Computer
    Science
  • Given a randomly ordered vector/array, sort it
  • ascending
  • descending
  • Many algorithms exists
  • some in Chapter 11
  • we will discuss two of them Selection Sort
    (11.1.1) and Insertion Sort (11.1.2)
  • Analysis in 11.4

53
Selection Sort
  • N is the number of elements in array/vector
  • Find smallest element, move into 0th array/vector
    location
  • examine all N locations
  • 0 .. N-1
  • Find next smallest element, move into 1st
    location
  • 0th location is already the minimum
  • examine N-1 elements
  • 1 .. N-1
  • Find next smallest element, move into 2nd
    location
  • 0th and 1st locations are already the minimum two
    elements
  • examine N-2 elements
  • 2 .. N-1
  • Generalize
  • for kth element, 0 lt k lt N-2
  • - find the minimum between kth and last
    element (element with
  • index
    N-1) of array
  • - swap the kth element with the minimum one

54
Selection Sort The Code
  • void SelectSort(vectorltintgt a)
  • // pre a contains a.size() elements
  • // post elements of a are sorted in
    non-decreasing order
  • int j, k, temp, minIndex, numElts a.size()
  • for(k0 k lt numElts - 1 k)
  • minIndex k // minimal
    element index
  • for(jk1 j lt numElts j)
  • if (aj lt aminIndex)
  • minIndex j // new min,
    store index
  • temp ak // swap min and k-th
    elements
  • ak aminIndex
  • aminIndex temp

55
Insertion Sort
  • Insert 1st element before or after 0th
  • first 2 sorted
  • Insert 2nd element (element with index 2) in
    proper location
  • first 3 sorted
  • Generalize
  • insert kth element (element with index k) within
    first k elements
  • first k1 sorted
  • run this for all k between 1 .. N-1

56
Insertion Sort The Code
  • void InsertSort(vectorltstringgt a)
  • // precondition a contains a.size() elements
  • // postcondition elements of a are sorted in
    non-decreasing order
  • int k, loc, numElts a.size()
  • for(k1 k lt numElts k)
  • string hold ak // insert this
    element
  • loc k // location for
    insertion
  • // shift elements to make room for hold
    (i.e. ak)
  • while (0 lt loc hold lt aloc-1)
  • aloc aloc-1
  • loc--
  • aloc hold

57
Which one faster?
  • No exact answer! It may depend on the vector to
    be sorted
  • already ordered
  • totally disordered
  • random
  • Lets see how many iterations do we have in
    Selection Sort
  • Outer loop ? k 0 .. N-2
  • Inner loop ? j k1 .. N-1
  • N-1 N-2 N-3 .. 1 N(N-1)/2 (N2 N)/2
  • Worst case, best case, average case???
  • Complexity is O(N2)
  • order of N2
  • Big-oh notation used to describe algorithmic
    complexities. This is not a precise amount of
    operations and comparisons. Minor terms and
    coefficients are not taken into consideration

58
Which one faster?
  • Lets analyze Insertion Sort
  • Outer loop ? k 1 .. N-1
  • N-1 iterations for the outer loop
  • What about inner loop?
  • worst case, best case differ
  • worst case k times, so total is 123N-1
    N(N-1)/2, complexity is O(N2)
  • best case inner loop does not iterate,
    complexity is O(N), but best case complexity
    analysis is not done too often
  • what are the best and worst cases?
  • average case inner loop iterates k/2 times,
    order is still O(N2)
  • Complexities of both Selection and Insertion Sort
    are O(N2)
  • Which one would you prefer to use?
  • Lets run timesorts.cpp (modified from book)
    needs several Tapestry .h and .cpp files in the
    project folder to run (comparer.h, ctimer.h,
    ctimer.cpp, prompt.h, prompt.cpp, randgen.h,
    randgen.cpp, sortall.h, sortall.cpp red ones to
    be added to the project).
  • Use the files provided in lecture notes (not the
    ones in book's website)
Write a Comment
User Comments (0)
About PowerShow.com