58
CS201 – Introduction to Computing – Sabancı University 1 2nd Midterm Exam December 5th, 2015, Saturday 10:00 – 12:00 Places are below (according to last name) FASS G022: Açılan – Barış FASS G049: Başdal – Çelik FASS G052: Çetin – Erdurgut FASS G056: Eren – Gez FENS L045: Ghanem – Kolaşin FASS G062: Korkmaz – Sertbaş 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 won’t 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.

2nd Midterm Exam

  • Upload
    venice

  • View
    37

  • Download
    0

Embed Size (px)

DESCRIPTION

2nd Midterm Exam. December 2 6 th , 2008, Fr i day 1 7 :40 – 1 9 :20 Places w ill be announced later - PowerPoint PPT Presentation

Citation preview

Page 1: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 1

2nd Midterm Exam December 5th, 2015, Saturday

10:00 – 12:00 Places are below (according to last name)

FASS G022: Açılan – Barış FASS G049: Başdal – Çelik FASS G052: Çetin – Erdurgut FASS G056: Eren – Gez FENS L045: Ghanem – Kolaşin FASS G062: Korkmaz – Sertbaş 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 won’t 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.

Page 2: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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, 19:40 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.

Page 3: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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.

Page 4: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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.

Page 5: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 5

7th and last homework

7th and last homework will be assigned this week Due December 16 Wednesday, 19:00 About vectors This week recitations will be about vectors and this

homework

Page 6: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 6

What’s 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

Page 7: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

Page 8: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 structstring 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 variablestudent stu;

stu.name = "Ali";stu.gpa = 4.0;cout << stu.gpa;

See structdemo.cpp (not in book)

stuid

4.0

gpa

Aliname

lastname

Page 9: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 9

What can and can’t 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 >> and <<) 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

Page 10: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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.

Page 11: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 11

Vectors Vectors are a class-based version of arrays We’re using the standard C++ class called vector

At the beginning of the program you have to have #include <vector>

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

Page 12: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

Page 13: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 13

ExamplePrevious example using vectors - see randnums.cpp int num;int k;RandGen random;vector<int> randStats(7); // vector for countersint n = PromptRange("how many random numbers",1,20000); for(k=0; k <= 6; k++) // initialize counters to zero{ randStats[k] = 0;} for(k=0; k < n; k++) // pick all random numbers{ num = random.RandInt(7); // between 0 and 6 randStats[num] = randStats[num] + 1; // and increment // corresponding counter} cout << "number\t\t# of occurrences" << endl;for(k=0; k <= 6; k++){ cout << k << "\t\t" << randStats[k] << endl;}

0 1 2 3 4 5 6

randStats

Page 14: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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)

vector<int> ivals(10); // ivals can store 10 intsivals[0] = 3; // 0th element becomes 3vector<string> svals(20); // svals can store 20 stringssvals[4] = "cs201"; // 4th element contains "cs201"

Page 15: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 15

Vector basics Syntax of vector declaration

vector is a class, its declaration is construction 3 different methods

vector<type> variable_name;

empty vector (will see later)

vector<type> variable_name (size_expression);

vector with size_expression elements in it

vector<type> variable_name (size_expression, init_value);

vector with all size_expression elements, all initialized to init_value

Page 16: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 <int> letters (int('Z')-int('A') + 1);• creates a vector of 26 integer elements and name it letterscin >> num;vector <double> 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

Page 17: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 17

Defining vector objects Can specify # elements in a vector, optionally an initial value vector<int> counts(300); // 300 ints, values not initialized vector<int> nums(200,0); // 200 ints, all zero vector<double> d(10,3.14); // 10 doubles, all pi vector<string> w(10,"cs");// 10 strings, all "cs" vector<string> 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 vector<Dice> cubes(10); since Dice doesn’t

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)

Page 18: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 18

Example vector definitions

vector<int> counter(9, 0);

each element is an integer(all initialized to 0) 0 1 2 3 4 5 6 7 8

counter

0 1 2 3 4 5 6 7 8

letters

9 10 11 12 13 14 15 16 17

vector<char> letters(18)each element is a char (not initialized yet)

0 1 2 3 4 5

holidaysvector<Date> holidays(6);

each element is a date object

that contains todays date24112015

24112015

24112015

24112015

24112015

24112015

0 0 0 0 0 0 0 0 0

Page 19: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

vector<int> nums(9);

nums[5] = 102;

nums[0] = nums[5]*2-1;

nums[nums[5]/20-3] = 55;

nums[10] = 5; // error

0 1 2 3 4 5 6 7 8

nums

102203 55

Page 20: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 (vector<int> & counts);

Pass by const-reference (if no changes made). • void Print(const vector<int> & 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)

Page 21: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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)

Page 22: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 22

vector as a return type

Vector can be return type of a function vector<int> Count (istream & input, int & total);

Example: modify letters.cpp such that count returns the vector (not as reference parameter) see letters2.cpp

Page 23: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 23

Vectors of structs We can define vectors of structs

struct student

{

unsigned int id;

string name, lastname;

double gpa;

};

vector<student> class(11);

// a vector with 11 students

class[1].gpa = 3.2;

for (i = 0; i <= 10; i++)

class[i].id = i + 1250;

1250

id gpa

name

lastname

1251

id3.2

gpa

name

lastname

1260

id gpa

name

lastname

0

1

10

class

Page 24: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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)

Page 25: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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, we’ll use a different method

for adding elements to the vector so that the vector can “grow”

Page 26: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 26

Reading words into a vector (problematic version)

vector<string> words(1000); string w; int i = 0; string filename = PromptString("enter file name: "); ifstream input(filename.c_str());

while (input >> w) {

words[i]=w; i++; } cout << "read " << i << " words" << endl;

What is the problem? there might be more than 1000 words in the file in this case, index runs out of range

Page 27: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 27

Reading words into a vector (with index range control but still problematic)

vector<string> words(1000); string w; int i = 0; string filename = PromptString("enter file name: "); ifstream input(filename.c_str());

while ((input >> w) && (i < 1000)) {

words[i]=w; i++; } cout << "read " << i << " words" << 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

Page 28: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

vector<string> words; //create empty vector string w; string filename = PromptString("enter file name: "); ifstream input(filename.c_str());

while (input >> w) {

words.push_back(w); //adds the next word to the vector //also increases the size if necessary

} cout << "read " << words.size() << " words" << endl;

Page 29: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 29

Using vector::push_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

Page 30: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 belowvector<string> 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

Page 31: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

Page 32: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

Page 33: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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)

Page 34: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 vector’s size - 1

int max (const vector<int> & v)//pre: vector v is not empty//post: return max of elements in v{

int i, max_so_far = INT_MIN;

for (i=0; i < v.size(); i++){

if (v[i] > max_so_far){

max_so_far = v[i];}

}return max_so_far;

}

Page 35: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 vector<int> & 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 assumptionint i =1;

while (i < v.size() && s == true) { //check until the end of array or until a counterexample is found

if (v[i-1] > v[i]) // if not sorted s = false; // counterexample is foundi++;

}return s;

}

Page 36: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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”

Page 37: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 37

Counting search (sequential)

int countmatches(const vector<string> & a, const string& s)// post: returns # occurrences of s in a{ int count = 0; int k; for(k=0; k < a.size(); k++) { if (a[k] == s) { count++; } } return count;} How can we change this code to return the index of the first

occurrence? see next slide

Page 38: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 38

One occurrence search (sequential)

int firstmatch(const vector<string> & a, const string& s)// post: returns the index of occurrence of s in a, -1 // otherwise{ int k; for(k=0; k < a.size(); k++) { if (a[k] == 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?

Page 39: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 39

Collecting search (sequential) Collect the occurrences in another vector

void collect(const vector<string> & source, vector<string> & matches)// pre: matches is empty// post: matches contains all elements of source with// first letter 'A'{ int k; for(k=0; k < source.size(); k++) {

if (source[k].substr(0,1) == "A") {

matches.push_back(source[k]); } }}

Page 40: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 you’re 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? let’s develop the algorithm on an example

• we need two index values, low and high, for the search space

Page 41: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 41

Binary Search (search for 62)

10 24 34 52 55 62 67 75 80 81 90 92 100 101 111

Low=0 mid=7 high=14

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low=0 mid=3 high=6

Low=4 high=6mid=5 => FOUND

Page 42: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 42

Binary Search (search for 60)

10 24 34 52 55 62 67 75 80 81 90 92 100 101 111

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low=4 high=4mid=4

Low=5 high=4 => NO MATCH FOUND – STOP

Low=0 mid=7 high=14

Low=0 mid=3 high=6

Low=4 high=6mid=5

Page 43: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 43

Binary search code

int bsearch(const vector<string>& 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 <= high) { mid = (low + high)/2; if (list[mid] == key) // found key, exit search { return mid; } else if (list[mid] < key) // key in upper half { low = mid + 1; } else // key in lower half { high = mid - 1; } } return -1; // not in list}

Page 44: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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)

Page 45: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 45

More vector processing: insertion and deletion

It’s 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 can’t 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

Page 46: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 46

Inserting an element into a sorted vector

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?

Example

Page 47: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 47

Insertion into sorted vector

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

0 1 2 3 4 5 6 7 8 9

Page 48: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 48

Insert into sorted vector

void insert(vector<int>& a, int newnum) // NOT const vector// pre: a[0] <= … <= a[a.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 > 0 && a[loc-1] > newnum) {

a[loc] = a[loc-1]; loc--; // shift right until the proper insertion cell } a[loc] = newnum; //actual insertion }

See vectorproc.cpp (not in book)

Page 49: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 49

What about deletion?

Remove the element at a given position (pos)

void remove(vector<string>& a, int pos)// post: original a[pos] removed, size decreased{ int lastIndex = a.size()-1; a[pos] = a[lastIndex]; a.pop_back();}

What about if vector is sorted, what changes? What’s the purpose of the pop_back() call?

Page 50: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 50

Deletion from sorted vector

2 7 11 18 21 22 26 89 99

0 1 2 3 4 5 6 7 8

Ex: Delete element at position 3

2 7 11 21 22 26 89 99 99

0 1 2 3 4 5 6 7 8

2 7 11 21 22 26 89 99 99

0 1 2 3 4 5 6 7

Size is 9

Size is now 8

First shift all elements on the right of 3rd element one cell to the left

pop back the last element of vector

Page 51: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 51

Deletion from sorted vector

void remove(vector<int> & a, int pos)// pre: a is sorted// post: original a[pos] removed, a is still sorted{ int lastIndex = a.size()-1; int k; for(k=pos; k < lastIndex; k++) { a[k] = a[k+1]; } //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)

Page 52: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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

Page 53: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 <= k <= 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

Page 54: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 54

Selection Sort: The Code

void SelectSort(vector<int> & 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(k=0; k < numElts - 1; k++) { minIndex = k; // minimal element index for(j=k+1; j < numElts; j++) { if (a[j] < a[minIndex]) { minIndex = j; // new min, store index } } temp = a[k]; // swap min and k-th elements a[k] = a[minIndex]; a[minIndex] = temp; }}

Page 55: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 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 k+1 sorted run this for all k between 1 .. N-1

Page 56: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 56

Insertion Sort – The Codevoid InsertSort(vector<string> & a)// precondition: a contains a.size() elements// postcondition: elements of a are sorted in non-decreasing

order{ int k, loc, numElts = a.size(); for(k=1; k < numElts; k++) { string hold = a[k]; // insert this element loc = k; // location for insertion

// shift elements to make room for hold (i.e. a[k]) while (0 < loc && hold < a[loc-1]) { a[loc] = a[loc-1]; loc--; } a[loc] = hold; }}

Page 57: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 57

Which one faster? No exact answer! It may depend on the vector to be sorted

already ordered totally disordered random

Let’s see how many iterations do we have in Selection Sort Outer loop k: 0 .. N-2

• Inner loop j: k+1 .. 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

Page 58: 2nd Midterm Exam

CS201 – Introduction to Computing – Sabancı University 58

Which one faster? Let’s 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 1+2+3+…+N-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? Let’s 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)