c++ ders8 - dizinler
DESCRIPTION
dizinlerTRANSCRIPT
![Page 1: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/1.jpg)
Built-in Arrays
� C++ native array type
� Two versions� fixed size arrays
� array size is fixed and must be specified with a constant expression at the declaration
� we will see this type now
� array pointers� array size is dynamically allocated
� we will not see it in this course
� use of both types are the same except definition
![Page 2: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/2.jpg)
Built-in Array declaration
� As we said, we will discuss fixed size built-in arrays, not the pointer version with dynamic allocation
� size must be able to be determined at compile time
� constant, literal or an expression that involves constants and literals only
const int CLASSSIZE = 100; // constant
string names[CLASSIZE]; // array of 100 strings
double grades[CLASSIZE*5]; // array of 500 doubles
int list[200]; // array of 200 integers
� The following array declaration is INVALID
int size;
cout "Enter how many students ? ";
cin >> size;
string names[size]; // array size cannot be a variable
![Page 3: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/3.jpg)
Built-in array initialization at declaration
� You may specify a list of initial values at declaration. See
following example:
string dayNames [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"};
� dayNames is an array with 7 elements of type string
� 0th element is “Sunday”, 1st is “Monday”, ...
� not necessary to specify size (7), since the number of elements make
the size clear
� but you can specify the size, if you wish
string dayNames [7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"};
![Page 4: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/4.jpg)
Assignment rules in arrays
� tvectors with the same element type can be assigned to
each other by =
� LHS vector becomes the same as the RHS vector
� size and capacity also become the same
� Built-in arrays cannot be assigned to each other by =
int coins[] ={1,5,10,25};
int temp[4];
temp = coins; // illegal
temp[1] = coins[2]; // legal – array element assignment
� How can we assign coins to temp?
� element by element
for (i=0; i<4; i++)
temp[i] = coins[i];
![Page 5: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/5.jpg)
Passing built-in arrays as parameters
� A built-in array can be passed only as reference
parameter or const-reference parameter
� cannot be passed as value parameter
� But, we do not use ampersand character, &, at
parameter declaration
� and we do not specify the array size in array parameter
� however array size is generally passed as another integer parameter since we do not have a size()
member function for built-in arrays
void Change(int list[], int numElts);
void Print(const int list[], int numElts);
reference parameter
const-reference parameter
![Page 6: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/6.jpg)
Built-in array demo
� See fixlist.cpp (slightly modified from the version in
book)
� Why did we use const in Print?
� to avoid accidental changes in array list
� Why did we pass numElts as parameter for the
number of elements in the array?
� because we don’t know the total number of elements in the
array while writing the functions
![Page 7: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/7.jpg)
Example – Fibonacci numbers� Used in many areas of Mathematics and Computer Science
F0 = 1F1 = 1Fn = Fn-1 + Fn-2
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
� You can see many examples of Fibonacci numbers in nature� E.g. Increase of number of branches of trees in time� See http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibnat.htmlfor more examples
const int MAX_SIZE = 100;
int list[MAX_SIZE];
int k;
list[0] = list[1] = 1;
for (k=2; k < MAX_SIZE, k++)
{
list[k] = list[k-1]+list[k-2];
}
![Page 8: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/8.jpg)
Arrays of structs
� We can define vectors of structs
struct student
{
unsigned int id;
string name, lastname;
double gpa;
};
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
id
3.2
gpa
name
lastname
1260
id gpa
name
lastname
0
1
10
![Page 9: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/9.jpg)
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 10: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/10.jpg)
Array Processing Examples – 1
� write a function that takes an array of integers as parameter and returns the maximum of numbers in it
� process all array elements – for loop from 0 to array’s size - 1
int max (int v[], int boyut)//pre: aray v is not empty//post: return max of elements in v{
int i, max_so_far = INT_MIN;
for (i=0; i < boyut; i++){
if (v[i] > max_so_far){
max_so_far = v[i];}
}return max_so_far;
}
![Page 11: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/11.jpg)
Array Processing Examples – 2 (vectorproc.cpp)
� Write a function that takes an array of integers as parameter and returns true if the array is sorted in ascending manner, false otherwise
� may not process all array 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 (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 assumption
int 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 sorteds = false; // counterexample is found
i++;}return s;
}
![Page 12: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/12.jpg)
Searching a vector� We can search for one occurrence, return true/false or the indexof occurrence
� Search the vector starting from the beginning
� Stop searching when match is found
� We can search and count the 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 count
� In all these cases, we search the vector sequentially starting from the beginning
� This type of search is called “sequential search”
![Page 13: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/13.jpg)
Counting searchint countmatches(const string[] a, int boyut,
const string & s)// post: returns # occurrences of s in a{int count = 0;int k;for(k=0; k < boyut; k++){ if (a[k] == s)
{ count++;
}}return count;
}
� How can we change this code to return the index of the
first occurrence?
![Page 14: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/14.jpg)
One occurrence search
int firstmatch(const string[] a, int boyut, const string& s)
// post: returns the index of occurrence of s in a, -1 // otherwise{int k;for(k=0; k < boyut; 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 15: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/15.jpg)
Collecting search� Collect the occurrences in another vector
void collect(const string[] a, int boyut, string[] matches)
// pre: matches is empty// post: matches contains all elements of a with// first letter 'A'{int k;for(k=0; k < boyut; k++){
if (a[k].substr(0,1) == "A"){
matches[k] = a[k];}
}}
![Page 16: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/16.jpg)
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� What number (between 1 and 100) do we guess first in number guessing game?
� 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
� 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 17: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/17.jpg)
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=6
mid=5 => FOUND
![Page 18: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/18.jpg)
Binary Search (search for 60)
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=6
mid=5
low=4 high=4
mid=4
low=5 high=4 => NO MATCH FOUND – STOP
![Page 19: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/19.jpg)
Binary search code
int bsearch(string[] list, int boyut, const string& key)// pre: boyut == # elements in list// post: returns index of key in list, -1 if key not found{
int low = 0; // leftmost possible entryint high = boyut-1; // rightmost possible entryint 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 20: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/20.jpg)
Comparing Sequential and Binary Search
• Given a list of N elements:
• Binary search makes on the order of log N operation
O(log N)
• Linear (sequential) search takes on the order of N operations
O(N)
Table 8.1 Comparing sequential / linear search with binary search Number of Items Examined (at worst)
List Size Binary Search Sequential Search
1 1 1
10 4 10
1,000 11 1,000
5,000 14 5,000
100,000 18 100,000
1,000,000 21 1,000,000
A Computer Science Tapestry page 375
![Page 21: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/21.jpg)
Sorting
� One of the fundamental operations in Computer
Science
� Given a randomly ordered 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 22: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/22.jpg)
Selection Sort
� N is the number of elements in vector/array
� Find smallest element, move into 0th vector/array location� examine all N elements
� 0 .. N-1
� Find next smallest element, move into first 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
� Generalizefor 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 23: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/23.jpg)
Selection Sort: The Codevoid SelectSort(int[] a, int boyut)// pre: a contains a.size() elements// post: elements of a are sorted in non-decreasing order{
int j, k, temp, minIndex;for(k=0; k < boyut - 1; k++){ minIndex = k; // minimal element index
for(j=k+1; j < boyut; j++){ if (a[j] < a[minIndex])
{ minIndex = j; // new min, store index}
}temp = a[k]; // swap min and k-th elementsa[k] = a[minIndex];a[minIndex] = temp;
}}
![Page 24: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/24.jpg)
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 25: C++ Ders8 - Dizinler](https://reader034.vdocuments.mx/reader034/viewer/2022052701/55cf8efa550346703b97a890/html5/thumbnails/25.jpg)
Insertion Sort – The Codevoid InsertSort(string[] a, int boyut)
// precondition: a contains boyut elements
// postcondition: elements of a are sorted in non-decreasing order
{
int k, loc;
for(k=1; k < boyut; 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;
}
}