0% found this document useful (0 votes)
9 views48 pages

Lecture 17

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views48 pages

Lecture 17

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

CS 101:

Computer Programming and


Utilization

Puru
with
CS101 TAs and Staff

Course webpage: https://www.cse.iitb.ac.in/~cs101/

Lecture 17: Searching, Sorting

Autumn 2019 CS101@CSE IIT Bombay


Passing 2 dimensional arrays to functions

void printmarks(char m[][20], int n){


for(int i=0; i<n; i++)
cout << c[i] << endl;
}

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
}

Autumn 2019 CS101@CSE IIT Bombay 2


Passing part of 2 dimensional

void printmarks(char m[], int n){


for(int i=0; i<n; i++)
cout << c[i] << endl;
}

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
}

Autumn 2019 CS101@CSE IIT Bombay 3


Arrays and memory
• Sequential/linear layout
• Row-major ordering for 2D arrays
• the [] binary operator
– if a is 1D array
– a[i] ==> *(a + i)

– if b is 2D array
– b[i][j] ==>

Autumn 2019 CS101@CSE IIT Bombay 4


Arrays and Recursion
• Recursion is very useful for designing algorithms on
sequences
– Sequences will be stored in arrays

• Topics
– Binary Search
– Merge Sort

Autumn 2019 CS101@CSE IIT Bombay 5


Searching an array
• Input: An array of length n storing numbers
• Output: true if a number is present in array, false otherwise.

• Natural algorithm: scan through the array and return true if found.

for(int i=0; i<n; i++){


if(A[i] == x) return true;
}
return false;

• 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.

• Can we possibly do all this with fewer operations?

Autumn 2019 CS101@CSE IIT Bombay 6


Searching a sorted array
• sorted array: (non decreasing order)
A[0] ≤ A[1] ≤ … ≤ A[n-1]

• sorted array: (non increasing order)


A[0] ≥ A[1] ≥ … ≥ A[n-1]

• How do we search in a sorted array (non increasing or


non decreasing)?
– Does the sortedness help in searching?

Autumn 2019 CS101@CSE IIT Bombay 7


Searching a non decreasing sorted array
• Assume array is sorted in nondecreasing order

• Key idea for reducing the number of comparisons:


First compare x with the “middle” element A[n/2] of the array

• Suppose x < A[n/2]: Because A is sorted, A[n/2..n-1] will also


have elements larger than x.
– x if present will be present only in A[0..n/2-1].
– So in the rest of the algorithm we will only search first half of A

• Suppose x >= A[n/2]:


– x if present will be present in A[n/2..n-1]
– x may be present in first half too, but if it is present it will be present in
second half too.
– So in the rest of the algorithm we will only search second half.

• How to search the “halves”?


– Recursion!
Autumn 2019 CS101@CSE IIT Bombay 8
Plan
• We will write a function Bsearch which will search a region of an
array instead of the entire array

• Region: specified using 2 numbers: starting index S, length of


region L

• When L == 1, we are searching a length 1 array.


– So check if that element, A[S] == x.

• Otherwise, compare x to the “middle” element of A[S..S+L-1]


– Middle element: A[S + L/2]

Algorithm is called “Binary search”, because size of the region to be
searched gets halved in every iteration

Autumn 2019 CS101@CSE IIT Bombay 9


The code
bool Bsearch(int A[], int S, int L, int x)
// Search in A[S..S+L-1]
{
if(L == 1) return (A[S] == x);
int H = L/2;
if (x == A[S+H]) return true;
if(x < A[S+H]) return Bsearch(A, S, H, x);
else return Bsearch(A, S+H, L-H, x);
}

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.

Autumn 2019 CS101@CSE IIT Bombay 11


Proof of termination
• Will the algorithm always terminate?

• Parameter L always decreases, unless it is already 1.


– Next call is with L/2 or L-L/2.
– So it will eventually become 1.
– So the base case will be reached.

Autumn 2019 CS101@CSE IIT Bombay 12


Remarks
• If you are likely to search an array frequently, it is useful to first
sort it.
The time to sort the array will be be compensated by the time
saved in subsequent searches

• How do you sort an array in the first place? Next.

• Binary search can be written without recursion. Exercise.

Autumn 2019 CS101@CSE IIT Bombay 13


Sorting
• Chapter 14 discusses a simple algorithm for sorting
called Selection sort

• Selection can require n2 comparisons to sort n keys

• Algorithms requiring fewer comparisons are known:


nlog n comparisons

• One such algorithm is Merge sort.

Autumn 2019 CS101@CSE IIT Bombay 14


Selection Sort

Autumn 2019 CS101@CSE IIT Bombay 15


Selection Sort (non-descending order)
void selSort(float data[], int N){
if(N == 0) return;

int maxIndex = argMax(data,N);

float maxVal = data[maxIndex];


data[maxIndex] = data[N-1];
data[N-1] = maxVal; // exchange

selSort(data, N-1)
}

Autumn 2019 CS101@CSE IIT Bombay 16


Merge sort idea
To sort a long sequence
• Break up the sequence into two small sequences
• Sort each small sequence (Recurse!)
• Merge the sorted sequences into a single long sequence

• Hypothesis: merging sorted sequences is easier than


sorting the large sequence

Autumn 2019 CS101@CSE IIT Bombay 17


Example
• Suppose we want to sort the sequence
– 50, 29, 87, 23, 25, 7, 64

• Break it into two sequences.


– 50, 29, 87, 23 and 25, 7, 64

Autumn 2019 CS101@CSE IIT Bombay 18


Example
• Suppose we want to sort the sequence
– 50, 29, 87, 23, 25, 7, 64
• Break it into two sequences
– 50, 29, 87, 23 and 25, 7, 64

• Sort both
– 23, 29, 50, 87 and 7, 25, 64

Autumn 2019 CS101@CSE IIT Bombay 19


Example
• Suppose we want to sort the sequence
– 50, 29, 87, 23, 25, 7, 64
• Break it into two sequences
– 50, 29, 87, 23 and 25, 7, 64

• Sort both
– 23, 29, 50, 87 and 7, 25, 64
• Merge
– to get 7, 23, 25, 29, 50, 64, 87

Autumn 2019 CS101@CSE IIT Bombay 20


Merge sort
void mergesort(int S[], int n){
// Sorts sequence S of length n.
if(n==1) return;

int U[n/2], V[n-n/2];


for(int i=0; i<n/2; i++) U[i]=S[i];
for(int i=0; i<n-n/2; i++) V[i]=S[i+n/2];

mergesort(U,n/2);
mergesort(V,n-n/2);

//”Merge” sorted U, V into S.


merge(U, n/2, V, n-n/2, S, n);
}

Autumn 2019 CS101@CSE IIT Bombay 21


Merging two sorted sequences
• Think of a sorted sequence as a row of students,
ordered shortest to tallest

• We are given two such rows, U, V

• We want to move students from both rows into a


new row S, but it should still be in shortest to
tallest order

Autumn 2019 CS101@CSE IIT Bombay 22


Merging
U: 23, 29, 50, 87.
V: 7, 25, 64.
S:
• The smallest overall must move into S.
Smallest overall can be smaller of smallest in U and
smallest in V.
• So after movement we get:
U: 23, 29, 50, 87.
V: -, 25, 64.
S: 7.

Autumn 2019 CS101@CSE IIT Bombay 23


What do we do next?
U: 23, 29, 50, 87.
V: -, 25, 64.
S: 7.
• Now we need to move the second smallest into S.
• Second smallest:
– smallest in U,V after smallest has moved out.
– smaller of the students currently at the head of U, V.
• So we get:
U: -, 29, 50, 87.
V: -, 25, 64.
S: 7, 23.

Autumn 2019 CS101@CSE IIT Bombay 24


General strategy
• While both U, V contain a student:
– Move smallest from those at the head of U,V to the end of S.
• If only U contains students: move all to end of S.
• If only V contains students: move all to end of S.
• uf: index denoting which element of U is currently at the
front.
– U[0..uf-1] have moved out.
• vf: similarly for V.
• sb: index denoting where next element should move into S
next (sb: back of S)
– S[0..sb-1] contain elements that have moved in earlier.

Autumn 2019 CS101@CSE IIT Bombay 25


Merging two sequences
merge(int U[], int p, int V[], int q, int S[], int n){
for(int uf=0, vf=0, sb=0; sb < p + q; sb++){
if(uf<p && vf<q){ // both U,V are non empty
if(U[uf] < V[vf]){
S[sb] = U[uf]; uf++;
} else{
S[sb] = V[vf]; vf++;
}
} else if(uf < p){ // only U is non empty
S[sb] = U[uf]; uf++;
} else { // only V is non empty
S[sb] = V[vf]; vf++;
}
}
}

Autumn 2019 CS101@CSE IIT Bombay 26


Remarks
• Recursion a power tool for manipulating data (in arrays)
as well

• Other sorting techniques


– Selection sort
– Insertion sort
– Merge without copying sub-arrays to new arrays
– How efficient?

• More examples in book for recursion and arrays


– Chapters 14, 15, 16

Autumn 2019 CS101@CSE IIT Bombay 27


Structures and Objects

Autumn 2019 CS101@CSE IIT Bombay 28


On Design
• Whenever you design something complex, it is useful to have a
plan
• Example: Plan for designing a building:
− Understand the requirements
− Understand the constraints: budget, land area
− Plan how many floors to have
− What should be on each floor
• A plan/methodology is also useful when designing large programs

Autumn 2019 CS101@CSE IIT Bombay 29


Object Oriented Programming
A Methodology for Designing Programs
• Clearly understand what is required and write clear specifications
(needed in all methodologies)
• Identify the entities involved in the problem
E.g., in a library management program: books, patrons
• Identify the information associated with each entity
− Fixed information: name of the book
− Variable information (state): who has borrowed the book at
present
• Organize the code so that the entities and their actions/inter
relationships are explicitly represented in the code
− Information associated with entities: structures
− Relationships/actions of entities: functions

Autumn 2019 CS101@CSE IIT Bombay 30


Outline
• Structure
− Basic facility provided in C++ to conveniently gather together
information associated with an entity
− Inherited from the C language
• Member functions
− New feature introduced in C++

Additional OOP ideas will come in later

Autumn 2019 CS101@CSE IIT Bombay 31


Structures: Basics Ideas
Structure = collection of variables (of possible different types)

Members of a structure: variables in the collection


Structure = super variable, denotes the memory used for all members
Each structure has a name, the name refers to the super variable,
i.e. entire collection

Each structure has a type: the type defines what variables there will
be in the collection

Autumn 2019 CS101@CSE IIT Bombay 32


Structure Types
• You can define a structure type for each type of entity that you
want to represent on the computer
Structure types defined by the programmer

– Example: To represent books, you can define a Book structure


type

• When you define a structure type, you must say what variables
each structure of that type will contain

– Example: In a structure to represent books, you may wish to


have variables to store the name of the book, price, etc.

Autumn 2019 CS101@CSE IIT Bombay 33


Defining a structure type
General form
struct structure-type{
member1-type member1-name;
member2-type member2-name;
...
}; // Don’t forget the semicolon!

Example
struct Book{
char title[50];
double price;
};

A structure-type is a user-defined data type, just as int, char, double


are primitive data types
Structure-type name and member names can be any identifiers

Autumn 2019 CS101@CSE IIT Bombay 34


Creating structure variables
To create a structure variable of structure type Book, just write:

Book p, q;

This creates two structures: p, q of type Book.


Each created structure has all members defined in structure type
definition.
Member x of structure y can be accessed by writing y.x

p.price = 399; // stores 399 into p.price.


cout << p.price; // prints the price of the book p

Autumn 2019 CS101@CSE IIT Bombay 35


Initializing structures
• Book b = {“On Education”, 399};

• Stores “On Education” in b.title (null terminated as usual) and 399


into b.price
• A value must be given for initializing each member
• You can make a structure unmodifiable by adding the keyword
const:

• const Book c = {“The Outsider”, 250};

Autumn 2019 CS101@CSE IIT Bombay 36


Nested structures (structure is a data type!)

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

Autumn 2019 CS101@CSE IIT Bombay 37


Assignment
One structure can be assigned to another

− All members of right hand side copied into corresponding


members on the left
− Structure name stands for entire collection unlike array name
which stands for address
− A structure can be thought of as a (super) variable

book b = {“On Education”, 399};


book c;

c = b; // all members copied


cout << c.price << endl; // will print 399

Autumn 2019 CS101@CSE IIT Bombay 38


Arrays of structures
Disk d[10];
Book library[100];

• Creates arrays d, library which have elements of


type Disk and Book

cin >> d[0].center.x;


• Reads a value into the x coordinate of center of 0th disk in array d

cout << library[5].title[3];


• Prints 3rd character of the title of the 5th book in array library

Autumn 2019 CS101@CSE IIT Bombay 39


Structures and Functions

• Structures can be passed to functions by value (members are

copied), or by reference

• Structures can also be returned.

This will cause members to be copied back.

Autumn 2019 CS101@CSE IIT Bombay 40


Parameter Passing by Value
struct Point{double x, y;};

Point midpoint(Point a, Point b){


Point mp;
mp.x = (a.x + b.x)/2;
mp.y = (a.y + b.y)/2;
return mp;
}

int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
cout << midpoint(p,q).x << endl;
}

Autumn 2019 CS101@CSE IIT Bombay 41


Parameter Passing by Value
• The call midpoint(p,q) causes arguments p,q to be copied to formal parameters
a,b
• When midpoint executes, the members of the local structure mp are set
appropriately
• The return statement sends back the value of mp, i.e. a nameless temporary
structure of type Point is created in the activation frame of main, into which mp
is copied
• The temporary structure is the result of the call midpoint(p,q)
• The temporary structure is copied into structure r
• r.x is printed
• The temporary structure can be used with the “.” operator, as in the second call.
Both will print x coordinate, 30, of the midpoint
• However, you may not modify the temporary structure. Writing midpoint(p,q).x
= 100; is not allowed. The value returned is considered const

Autumn 2019 CS101@CSE IIT Bombay 42


Parameter Passing by Reference
struct Point{double x, y;};

Point midpoint( const Point &a, const Point &b){


Point mp;
mp.x = (a.x + b.x)/2;
mp.y = (a.y + b.y)/2;
return mp;
}

int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
}

Autumn 2019 CS101@CSE IIT Bombay 43


Parameter Passing by Reference
• In the execution of midpoint(p,q) the formal parameters a,b refer
to variables p, q of main
• There is no copying of p, q. This saves execution time if the
structures being passed are large
• The rest of the execution is as before
• const says that a, b will not be modified inside function
− Helps humans to understand code
− Enables const structures to be passed by reference as
arguments
midpoint(midpoint(..,..),..)

Autumn 2019 CS101@CSE IIT Bombay 44


A Structure to Represent 3 Dimensional Vectors

• Suppose you are writing a program involving velocities and


accelerations of particles which move in 3 dimensional space
• These quantities will have a component each for the x, y, z
directions
• Natural to represent using a structure with members x, y, z
• struct V3{ double x, y, z; };

Autumn 2019 CS101@CSE IIT Bombay 45


Using struct V3
• Vectors can be added or multiplied by a scalar. We might also
need the length of a vector.

V3 sum (…) {

V3 scale( … ){

double length(… ){

}

Autumn 2019 CS101@CSE IIT Bombay 46


Using struct V3
V3 sum(const V3 &a, const V3 &b){
V3 v;
v.x = a.x + b.x; v.y = a.y + b.y; v.z = a.z + b.z;
return v;
}

V3 scale(const V3 &a, double f){


V3 v;
v.x = a.x * f; v.y = a.y * f; v.z = a.z * f;
return v;
}

double length(const V3 &v){


return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}

Autumn 2019 CS101@CSE IIT Bombay 47


example
• If a particle has an initial velocity u and moves under uniform acceleration a, then
in time t it has a displacement s = ut + at2/2, where u, a, s are vectors

• 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

cin >> u.x >> u.y >> u.z >>


a.x >> a.y >> a.z >> t;

s = sum(scale(u,t), scale(a, t*t/2));

cout << length(s) << endl;


}

Autumn 2019 CS101@CSE IIT Bombay 48

You might also like