Lecture 17
Lecture 17
Puru
with
CS101 TAs and Staff
int main(){
// array to store marks of 3 courses
char marks[3][20]= … // as before
printmarks(marks, 2);
// will print out only first two courses
}
int main(){
// array to store marks of 3 courses
char marks[3][20]= … // as before
printmarks(marks[0], 2);
// will print out only first course
}
– if b is 2D array
– b[i][j] ==>
• Topics
– Binary Search
– Merge Sort
• Natural algorithm: scan through the array and return true if found.
• Time consuming: we will scan through entire array if the element is not
present, and on the average through half the array if it is present.
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 10
How does the algorithm execute?
• A = {-1, 2, 2, 4, 10, 12, 30, 30}
• First call: Bsearch(A, 0, 8, 11)
– comparison: 11 < A[0+8/2] = A[4] = 10
– Is false.
• Second call: Bsearch(A, 4, 4, 11)
– comparison: 11 < A[4+4/2] = A[6] = 30
– Is true.
• Third call: Bsearch(A, 4, 2, 11)
– comparison: 11 < A[4+2/2] = A[5] = 12
– Is true.
• Fourth call: Bsearch(A, 4, 1, 11)
– Base case. Return 11 == A[4]. So false.
selSort(data, N-1)
}
• Sort both
– 23, 29, 50, 87 and 7, 25, 64
• Sort both
– 23, 29, 50, 87 and 7, 25, 64
• Merge
– to get 7, 23, 25, 29, 50, 64, 87
mergesort(U,n/2);
mergesort(V,n-n/2);
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