Lecture18
Lecture18
Puru
with
CS101 TAs and Staff
• Topics
– Linear search, Binary Search
– Insertion sort, Selection Sort, Merge Sort
int main(){
int A[8]={-1, 2, 2, 4, 10, 12, 30, 30};
cout << Bsearch(A, 0, 8, 11) << endl;
// searches for 11.
}
Autumn 2019 CS101@CSE IIT Bombay 3
Merge sort
void mergesort(int S[], int n){
// Sorts sequence S of length n.
if(n==1) return;
mergesort(U,n/2);
mergesort(V,n-n/2);
• Member functions
− New feature introduced in C++
− Actions that effect the entity
Each structure has a type: the type defines what variables there will
be in the collection
• When you define a structure type, you must say what variables
each structure of that type will contain
Example
struct Book{
char title[50];
double price;
};
Book p, q;
struct Point{
double x,y;
};
struct Disk{
Point center; // contains Point
double radius;
};
Disk d;
d.radius = 10;
d.center = {15, 20};
// sets the x {member of center member of d
copied), or by reference
int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
cout << midpoint(p,q).x << endl;
}
int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
}
V3 sum (…) {
V3 scale( … ){
double length(… ){
…
}
• To find the distance covered, we must take the length of the vector s
int main(){
V3 u, a, s; // velocity, acceleration, displacement
double t; // time
• In C++, you can make the functions a part of the struct definition
itself.
Such functions are called member functions.
struct V3{
double x, y, z;
int main(){
V3 v={1,2,2};
cout << v.length() << endl;
}
int main(){
V3 u, a, s;
double t;
cin >> u.x >> u.y >> u.z >> a.x >> a.y >> a.z >> t;
V3 ut = u.scale(t);
V3 at2by2 = a.scale(t*t/2);
s = ut.sum(at2by2);
struct Queue{
int elements[N], nwaiting,front;
bool insert(int v){
…
}
struct Queue{
…
bool insert(int v){
if(nWaiting >= N) return false;
elements[(front + nWaiting)%N] = v; nWaiting++;
return true;
}
};
• The member functions only contain the logic of how to manage the
queue
• The main program only contains the logic of dealing with taxis and
customers
string message;
getline(cin, message);
int mx = message.size()-1;
while (mx >= 0) { Character at
position mx in
cout << message[mx]; string
--mx; message
}
• mx updated in a completely predictable way
• Ideal candidate to write as for loop
Autumn 2019 CS101@CSE IIT Bombay 52
Finding needles in a haystack
while (true) {
ans += base/fac;
base *= x;
fac *= (++ix);
if (base/fac < epsilon) {
break; Terminates
} immediately
cout << (base/fac) << endl;enclosing
while loop
}
Autumn 2019 CS101@CSE IIT Bombay 58