Dsa Notes
Dsa Notes
CONLENRY COPY
Rer
e
APBORiTAM
1.1.ALGORITHMS: AN INTRODUCTION
An algorithm is a set of rules that must be followed when solving a specific
problem. The problem can be solved either by hand, usually, on a
or more
machine. Informally, we can also define an algorithm as a well-defined computa-
tional procedure which takes some value or set of values as input and generates
some value or set of value as output. The result of a given problem is the output
that we get after solving the problem. An algorithm is thus defined as a finite
the given input into the output
sequence ofcomputational steps that transforms to be correct, if for every input
for a given problem. An algorithm is considered terminated. Thus a correct
instance, it generates the correct output and gets
desired output
algorithm solves a given computational problem and gives the
value. On the contrary, we can say that the incorrect algorithm does not
terminate on the desired output for the input instance or might terminate for
some other output value other than the desired one.
Description
Every algorithm includes a briefdescription of the tasks that it performs. It
includes the name, type of a variable used and also the assumptions (if any).
For examnple:
Algorithm Bubblesort
This algorithm sorts the elements of given array 'A' in an ascending
(increasing) order. The array contains 'n'number of elements. The variable pc'
denotes the pass counter and lu' refers to the last unsorted elements. To count
the number of exchanges performed on any pass variable 'ex' is used.
Comment
The symbol ' indicates the comment. The comment specifies no action
and is taken only for clarity.
For example: Compareelement Ali] with Ali + 1]
Steps
Every algorithm contains steps to accomplish the particular task. Each step
begins with the phrase written in square bracket that sums up as briefly as
possible the principal content of that step.
For example:
Step 1 Initialisation]
setlu-n
set n n +1
Operators
For simplicity and clarity, we use mathematical language which includes
algebra and set theory. Basically, operators are the symbols which operates on
the operands. The operands are either constant values or consist of expressions.
The arrow "", performs the replacement operation, sometimes called
assignment or substitution.
For example : m-l
In the above statement, the value ofvariable 'm'is replaced by the current
value of variable ' . For clarity we have used a term 'set' to perform an
action.
Algorithms
and Analysis of
4 OO The Demign
-ner
set temp m
set m - n
set m temp
Variables
Variables can either be local or global. All variables are treated as local
variables if not explicitly specified as global.
The element of an array can be accessed by specifying the array name
followed by the index in the square brackets.
For example:
Alil, indicates the ith element of an array A. The length of an array is
specified by:
length A]
Scalar parameters are passed by value, that means
aslocal variables within "procedure" or
they are considered
"function". The array
are passed by reference, which means the same effect can beparameters
seen in an
array as in the "procedure" or "function".
Algorithm O05
Conditional Statements
These statements are executed
depending upon the condition specified.
It includes the 'if statements which takes the three form
aif
oif else
Dif-else-if
of AlgoPILli
Analysis
and
The Design
6 00
i f statements
if (expression) then
if-body
setb-6
if(a> 4) then
set a - a + 1
set b - a +1
After the execution of above statement, the final value of variable 'a' is6
and variable 'b' is 7.
if-else statements
if (expression) then
if-body
else
Algorithm OO7
else-body
In the above
statement, if the expression evaluates "true" then 'if-body'
statements are executed and control is transferred at the end of "
if-body"
ignoring the else-body). Otherwise, the 'else-body' statements are executed and
control is transferred at the end of
'else-body'.
For example:set a -5, b - 6 > assigning values
ifa> 6)
set a-a +1
set b -b +1
else
set a - a -1
setb-b-1
After the execution of above statement, the final value of variable 'a' is 4
and variable 'b' is 5, since expression evaluates false.
if-else-if statement
if (expression) then
Algorithms
and Analysis of
10 O0 The Design
case constant 3
default
statement".
For example:set a 5 , b-6, ch-2
select case (ch)
case1
set a-a +1,b-b+1
return
Algorithm OO 11
case 2
set a a + 2, b b + 2
return
case 3
set a a + 3, b +b+3B
return
default
set a - a + 4, b -b+ 4
caseconstant 1:
caseconstant 1:
case constant 2:
14 CO The
Design and Analysisof Algorith
= = ] statements
count +1
set count-
Forexample:
setq-5
2, > (ns 10)
Repeat forcount- 1,
--n
incrementing qby 5.
setq-+5
of above statements the final valito
variable "¢i
se
count2 step 2
15
count3 step 3
20
count4 step 4
25
count 5 step 5
30
count 6 step 6
g-35
count7 step 7
40
count8 step8
45
count 9 step 9
-50
count 10 step 10
55
Now, if"count" increments then its value exceeds the last "sequential value"
and loop terminates.
count-2
a <b, true
a3
Algorithms
Analysis of
OO The Design and
16
count3
a <b, true
a4
count4
a <b, true
a5
"false" thus the loop terminates.
condition becomes
Now, the
Unconditional Statements transter of the control. The
statements cause
an unconditional
These :
statements are of following types
unconditional
go to
Oexit loop
O exit. unconditional transfer ofthe controlto
causes an
The "go to statement" the control to transfer to
"go to step 3"
causes
the specified step.Thus
called steps).
in between calling and
step 3 (omitting all the steps
causes
unconditional transfer of the control
T h e "exit loop statement" it immediate exit
causes an
That means
outside the loop (or brackets).
The "exit loop
works
statement"only for one
from the loop (or brackets). one loop is nested within
are there and
level. Thus, if nested loops
statement of inner loop causes
of "exit-loop"
another, then the execution
to transfer the control to
the outer loop.
is written as the last step, which
The "exit statement" statement
terminates the whole algorithm.
It should be noted that the above
mentioned unconditional statements leads to unstructured algorithm,
so these statements
should be avoided. The whole text book takes the
are used only
advantage of structured algorithms but these statements
when the alternatives are awkward.
For example:
Now, consider an example that sorts a given list of items.
1.5. ALGORITHM BUBBLESORT
This algorithm sorts the element of an array 'A' (having n elements) in the
and
(increasing)order. The counter is denoted by variable P
ascending
the variable 'E' is used
pass
to count the number of exchanges performed on any
pass. The last unsorted element is referred by variable ".
Ste Initialization
set 1- n,p 1
Step2 10op
Repeat through step 4while (p Sn 1)
set E0 Initializing exchange variable,
Step 3 comparison, loop.
Repeat forie1,1,...l-1
Algorithm O0 17
(n 2) comparisons.
largest element is placed at An 1]
by performing
-
After n 1 passes we
get the
-
final
sorted list as:
A SA2SA3S...A-1SA
The whole list of 'n' elements of an
array 'A"'is sorted after (n 1) passes. -
Example 1.1. Following lists of elements are given, and we have to sort the
given list in an ascending order using Bubblesort.
45, 60, 40,95, 75,35, 25,65.
The whole process is illustrated below:
Solution: The Bubble sort process is given
show the comparison.
below. The encircled elements
Initially,
G5 6
45 60 40 95 75 35 25 65
65
Pass 1
Compare a and aj
a4 5
45 40 95 75 35 25 65
as a a S0 no change in the resultant list.
Compare a, and a2
a1 a4 5 6 O7
45 95 75 35 25 65
as a a g so the resultant list is.
of Algorithms
and Analysis
18 O0 The Design
a6
a3 4 65
a2 35 25 1.6. SUBALGORITHM
95 75
45 40 60 The main algorithm
Comparea, and a3 subalogorithm is a co
2 a4
65
designed to performn
75 35 25 control of the main
45
45 40 algorithm can use it
resultant list.
s0 no change in the The subalgorithm an
as
a2 ag,
program and main pr
Compare ag and a4
a4 performs computatio
a1
25 65 routine. It should be
45 40 60 95 (75) 35
terminating the algo
So the resultant list is
nating the subalgoritt
as
ag a4,
5
a1 a3 4
95 35 25 65 [Procedure/F=
45 40
40 60 75 The subalgorit
Compare a, and ag Function subal
a6 of a Procedure
a2 value of the fur-
25 65
45 40 60 75 95 1.6.1. FUNCTION SUE
resultant list is.
asa>ag, So the Function subalgo-
a1 a2 ag 4 a5 tine. It usually has tE
60 75 35 95 25 65
45 40
Compare a, and Function Subal
a1 4 a6 The returning of
statement 'return (v
45 40 60 75 35 95 25 65
as aga6, So the resultant list is Example 1.2. The fo
rameters and return
a2 4 a5 a6
45 a Solution
45 40 60 75 35 25 95 65.
Compare ag and a Function Add (=
ag a4 a5 a6 The abovefunc
45 40 60 75 35 25 95 65 2 All variables are
variable w' which
as aga7, So the resultant list is
Step 1 com
do 1 d2 4 a5 a6 a7
45 40 60 75 35 25 65 95. set
A t the end of first pass, the largest element 95 has moved to the last posi Step 2retu
tion i.e., dq retu
The main algori
4
45 40 60 775 35 s25 a6 65 95
part of an expressio
A t the end of second pass, the second largest element 75 has moved to the For example: A
set
second last position ie., ag
It should be not
a7 the parameters of e
40 45 60 35 25 65 75 95 is executed then th
The process continues till
pass 7 where the seventh largest element has to ' . After the exe
moved to the position a. Thus, we get the sorted list after n 1 passes. -
variable'w' is retur
2 4 5 a6 statement. Finally
25 35 40 45 60 65 75 95
Algorithm O0 19
1.6. SUBALGORITHMM
ithm
The main algoriti can call zero, one or more than one subalgorithm. A
alogorithm is a complete and independently defined algorithm module. It is
sub
form
desigmed to perfor some computational tasks, whereever necessary under the
control of the main algorithm. It is defined independently so that different
algorithm canuse it or even the same algorithm can invoke it number of times.
The subalgorithm and main algorithm have the same relationship as the sub-
program and main program have in a programming language. A sub algorithm
performs computatIon on zero or more parameters provided by the calling
routine. It should be noted that the main algorithm uses 'exit statement' for
terminating the algorithm and subalgorithm uses 'return' statement for termi-
nating the subalgorithm. Usually subalgorithm takes the following form:
[Procedure/function] subalgorithm name (par 1, par 2 par n)
The subalgorithm can be of two types either 'procedure subalgorithm or
Function subalgorithm'. The statement return' marks the dynamic end
of a Procedure' or a Function' and in the latter case it also supplies the
value of the funetion.
1.6.1. FUNCTION SUBALGORITHMM
Function subalgorithm explicitly returns the single value to the calling rou-
Example 1.2.The following function subalgorithm adds the values of the pa-
rameters and returns the added result to the calling routine.
Solution:
Funetion Add ( ,, 2
T y and
The above function subalgorithm adds the values of variables
stored in
All variables areassumed tobeof type real. The addedresult is
variable w which is returned to thecalling routine.
Step 1 computing, sum
setwx+y+
Step 2 return, computing result
return (uw)
The main algorithm involves the function subalgorithm 'Add' as an implicit
part of an expression.
For example: An algorithm contains following statement.
set sum - Add (i,j, k)
It should be noted that there should be one to one correspondence between
parameters of called and calling routines. Thus when the above statement
the
1s executed then the value of i is copied to ' ' , f is copied to y and '*' is copied
to 2. After the execution of subalgorithnm 'Add' the computing result value of
kY in the
variable 'w' is returned to calling subalgorithm and replaces Add (i,j,
Statement. Finally, the variable 'sum'holds the value of the variable
and Analysis ofAlgorithms
The Design
20 0 0
1.6.2. PROCEDURE SUBALGORITHM
no
icitly returned to the
value is explicit calling routine.
subalgorithm e than one value t
more:
In
Procedure wants to
return
the cal:
used when one
implicitly through parameters
hurned implicitly parameters. It will us
Infact,it is
routine. All values
are
returned
form
ually
have the
heading ofthe par n)
Subalgorithm (par 1, par 2,-
Procedure
for Procedure Subalgorithm
example
Consider following
following Procedure
Subalgorithm swaps the
the values
valuee.
of
Krample 1.3. The the
return implicity.
parameters,
all values
Procedure Add,y, 2, u
Theabove Procedure Subalgorithm adds the value to the variable
and 2. Variable u holds the computed result of the addition. All variables
are assumedto be of type real.
Step 1 computing, sun
Setw +y+2
Step 2 returning, at point of call
return
1.7. ANALYSING ALGORITHMS
Analysis of algorithm depends
communication bandwidth, or upon various factors such as
the computer hardware. But the most often memory
computational
task. As
time that an
algorithm requires for completing theusea
1
Average case
Best case
N
2 3
Fig. 1.1.Time-complexity
The worst case time complexity is the function defined
by the maximum
amount f time needed by an algorithm for an input of size, 'n'. Thus, it is
the function defined by the maximum number of taken on
steps any
instance of size 'n'.
The average case time complexity is the execution
of an algorithm having
typical input data of size 'n'. Thus, it is the function defined by the average
number of steps taken on any instance of size 'n'.
The best case time complexity is the minimum amount
of time
that aan
algorithm requires for an input of size 'n'. Thus, it is the function defined
by the minimum number of steps taken on any instance of size 'n'.
t should be noted that all these time
function time vs size.
complexities define a numerical
Design
The
22 O O
A, n)
the elements of an
Insertionsort
P r o c e d u r e S u b a l g o r i t h m
sorts
n' 'number of element
array 'A:
The
Procedure
The array
consists of n
variable,
The variable
order. a temporary
ascending and ?' is
for index [A]
fis used
uptil length
for i 2 , 3, 5,
Step 1
Loop, 4, -n
2. sett-A] n - 1
Ca
3. setp -i-1
>0 and t <Ap))
CA i=2
4. Repeat while (p
1]-A(p]
C6 4-
5 set Alp +
setp-p -1
C6
6.
n-1
1)-t C
7. set Alp +
rall
results in over
'cost' for comments is '0' which the tota
It should be noted that the executable s t a t e m e n t s . Thus,
z e r o running
time as comments a r e not
as
Tln) c a n be expressed
running time of an algorithm - 1)
l = 2
nn+1)-1
2
and
Tt)=Cn+G(i -1)+C,n-i)+c -1
+C(n-1)
2 2
40 10 80 20 60 50
30
Step 2
pass 2
2
40 10 80 20 60 50
70
Step 3
pass 3
ds 6
30 70 10 80 20 60 50
Step 4
pass 4
6
30 40 70 1 80 20 60 50
Step 5
pass 5
o as 6
10 30 40 70 20 60 50
Step 6
pass 6
10 30 40 70 80 20 60 50
Step 7
pass 7
10 20 30 40 70 80 50
Step 8
pass 8
10 20 30 40 60 70 80
Sorted array
a4 ag
10 20 30 40 50 60 70 80
1.8. DESIGNING ALGORITHM
Various designing techniques are available for algorithms. Here we will disc
two designing approach
of algorithm:
Algorithm O0 25
Incremental approach.
Divide and conquer
Approach.
1.8.1. Incremental Approach
In this
approach whenever element is inaerted into its appropriate
a new
place, index is increased. Previously discussed
on this insertionsort algorithm is baased
approach; which we have sorted
in
of new
element A[] into appropriate placesubarrayA[1],
yields sorted
A[2] Ali -1), insertion
subarray A[1), A|2)
Ali 11 A[i].
Here,
based
we are
presenting another sorting method 'selection sort' which is
on this
approach. In selection sort
are selected in order method, all the successive elements
and placed into their
begins by finding the least element which isappropriate positions. Thea method
After finding the least accomplished by making search.
element, it is then interchanged with the first element.
Next, second smallest element is
whole interchanged with the second element. The
process continues until the whole list is sorted.
Procedure Selectionsort (A, n)
The above Procedure
Subalgorithm sorts given element of an array
A' of n number of elements in an ascendingthe order. The
that is located in particular pass is denoted by variable 'S'.smallest element
The variable p
denotes the index of a pass and position of the first element which is to be
examined during a particular pass.
Step 1 loop, repeated (n-1) times
Repeat through step 3for p1,2,3
set S-p
Step 2 element with smallest value is obtained in every pass
Repeat step 2for i -p+1,p+2n
if(A[S]> A[il) then
set S-i
End of step 2 loop
Step 3 Exchanging the values
if(S#p) then
set Alp]+ A[S]
End of step 1 loop
Step 4 Finish
return
Analysis
It should be noted that while calculating the running time of selection sort
algorithm, the exchangingstep breaksdown into three individual step as
sett-Alp]
setAlp]-Als]
set A[s) - t
Now, collecting all we have the following running time Tn):
26 00 The Design and Analysis of Algorithms
Selectionsort ( A, n) Cost
Times
1. Repeat through step for p- 1, 2,... n -
1
C Step 2
2. set S - PP Ca - 1
pass 2
S 5
3.
Repeat step 3 foriep+1.p+ 2 . C3
P 1
7. set t-Ap]
C
Step 5
8. setA[p]-A[s] Cs Pass 5
-1
p 2
S=7
9. set A[s] - t
C9 2-1
P=2
Step 6
Tn)
G,n)+C;(n -1)+c P=1
+C +C, -1)
pass 6
S 6
p=1 p 2
Ca ,-1)+c, ,-1)+C ,
P=l -1)+C,, -1)
P-2 P=2 Step 7
P 2
Example 1.6. Let us suppose an array consists of 8 pass 7
elements as S= 7
70, 30, 40, 10, 80, 20, 60, 50.
and we have to sort the
elements in an
method. The whole process is ascending order using selectionsort
illustrated below.
Solution : The encircled elements
denote the smallest key selected Sorted
pass, which is then in a particular
exchanged.
Step 1
pass 1
S 3
1.8.2.
as Mc
70 30 40 80 20
partic
60 50 algorit
In thie
Algorithm O0 27
Step 2
pass 2:
S=5
a2
10 30 40 70 80 20 60 50
step 3
Pass 3:
S 5
o
as
10 20
40 70 80 60 50
Step 4
Pass 4:
S 5
3 as
10 20 30 70 80 60 50
Step 5
Pass 5
S=7
2 as
10 20 30 40 80 70 60 50
Step 6
pass 6
S=6
a6
10 20 30 40 50 70 60 80
Step 7
pass7
S= 7
6
10 20 30 40 50 60 80
Sorted array
d2 5 d6
10 20 30 40 50 60 70 80
1.8.2. Divide and Conquer Approach
Most of the algorithms are recursive in nature. That means, for solving a
particular problem they call themselves repeatedly one or more times. Al these
agorithms follow the divide and conquer approach to accomplish the given task.
n this approach, whole problem is divided into several subproblems. These
Design
and Analysis of Algorithms
28 O0 The
oblem
problem but small
Bmaller insize. All
to the original
subproblems
are
similar
recursively. The solutions obtained om
from
these
are then solved
create a solution to the orioin the.
the
subproblems combined to
are then
subproblems
At blems
each levelof the recursion the divide and conquer approach followsthree
steps
S t e p1 : Divide
In this step whole problem is divided into several subproblems
Step 2: Conquer
The subproblems are conquered by solving them recursivelu
they are small enough to be solved, otherwise step 1 is executed
Step 3 : Combine
Finally, the solutions obtained by the subproblems are combined t
create solution to the original problem.
Here, we are presenting a simple problem that can be solved by the divide
and conquer technique. The problem is to sort a given list of item using merge
sort. For solving the given problem it includes these steps as
Step1: Divide
The whole list is divided into two sublists of n/2 elements each for
sorting.
Step 2: Conquer
Sort the sublist recursively using mergesort.
Step 3: Combine
Now Merge the two sorted sublists to generate the sorted answer.
For accomplishing the whole task we are using two Procedu.res "Mergesort
and Merge'. In this section we are presenting the algorithm for procedure
"Mergesort' which takes the advantage of Procedure 'Merge'. Procedure 'Merge'
is used for combing the sublists.
recurslvel
Solving I sublist,
mid + 1, finish
Mergesort (A,
call
two sublists, sorted
Merging
mid +1, finish)
Shep6
call Merge (A, start,
Finish
return
Merge (A,
first, second, third)
dure the two lists and produces a
proceae Drocedure subalgorithm merges
T h ea b o v e p r o c e d u r e
new
is used for holding sorted values.
The Temporary
array temp'
sortedl i s t .
initialisation
Step 1 S - second
setn 0 , f - first,
element
Comparison, giving smallest
Step ifAIISASD then
+1
setn - n
set temp In)-AIN
setf-f+1
else
setn - n +1
set temp n]-A[S]
setS-S+1
elements
Stap3 Copying remaining
if (f2 second) then
loop
Repeat while (S S third)
set n - n +1
set temp [n]-A[S}
set S-S+1
End loop
else
loop
Repeat while (f< second)
setn -n +1
Bet temp Inj -A[S)
setf-f+ l
End of loop
Step 4 Copying, element to original array
loop
Repeat forf-1,2, - n
Alfirst-1+f1-temp f1
End of loop
Step 5finish
return