0% found this document useful (0 votes)
33 views

Algorithm ch-2

The document discusses algorithms and data structures including stacks, queues, and time complexity analysis. It provides details on common stack and queue operations like push, pop, and peek. Stacks follow LIFO while queues follow FIFO. Time complexity is evaluated based on best, average, and worst case scenarios and expressed using Big O notation. Memory requirements are also considered in analyzing algorithm efficiency.

Uploaded by

growingworld154
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Algorithm ch-2

The document discusses algorithms and data structures including stacks, queues, and time complexity analysis. It provides details on common stack and queue operations like push, pop, and peek. Stacks follow LIFO while queues follow FIFO. Time complexity is evaluated based on best, average, and worst case scenarios and expressed using Big O notation. Memory requirements are also considered in analyzing algorithm efficiency.

Uploaded by

growingworld154
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

COMPUTER ENGINEERING ALGORITHMS

Chapter – 2 Fundamentals Programming Models and String


1. Stacks
 In this the data element stores in order. A stack is data structure in which elements
are added and removed from one end, last in first out structure (LIFO) or First in
Last out (FILO).
 To represent a stack array is used. Stack is a linear data structure. In this list insertion
and deletions are made at one end called Top of Stack. It’s an abstract data type.
 For example – a deck of cards or a pile of plates, etc. A real-world stack allows
operations at one end only. For example, we can place or remove a card or plate
from the top of the stack only. Likewise, Stack ADT allows all data operations at
one end only. At any given time, we can only access the top element of a stack.
 There are mainly three basic operations:
 PUSH
 POP
 PEEK

 Representation of stack:Here is the stack representation is given in which elements


stores at one end called top. Stack is follow bottom upapproach.

 A stack can be implemented by means of Array, Structure, Pointer, and Linked List.
Stack can either be a fixed size one or it may have a sense of dynamic resizing. Here,
we are going to implement stack using arrays, which makes it a fixed size stack
implementation. Array representation of stack is given below.

1
COMPUTER ENGINEERING ALGORITHMS

 PUSH Operation:
 Algorithm:
 Step 1: Start
 Step 2: if Top >= n-1
Write “stack overflow”. Go to step 5.
 Step 3: Increment Top ← Top+1
 Step 4: S[Top] ← x
 Step 5: Finished
[Exit]

 POP Operation:
 Algorithm:
 Step 1: Start
 Step 2: if (Top=0) or (Top= -1)
Write stack is “under flow” go to step 6.
 Step 3: value ← s[Top]
 Step 4: Top ← Top-1
 Step 5: return value
 Step 6: Finished
Exit.

 Peek Operation:
 This operation is used to return the value of the topmost element of the stack without
deleting it.
 Algorithm:
 Step 1: start
 Step 2: if (Top=0)
then print “under flow” go to step 4.
 Step 3: Return s[Top]
 Step 4: Finished

 Application of the Stack:


 Representation of polished notation
 Recursion
 Stack Machine

2
COMPUTER ENGINEERING ALGORITHMS

2. Queues
 In queue we can work on both the end i.e. front and rear. Front end is used to delete
the element and the rear element is used to insert new element. The queue is work on
the concept of first in first out. i.e. FIFO
 A data structure in which elements are added from one end called rear and delete
from other end called front in FIFO structure known asqueue.
 It is same as stack. But difference is, queue is working on FIFO and stack is working
onLIFO.
ELEMENTS

Frontend rearend

[deletion/exit]
[insertion/entr
y]

 Operation on queue:
 There are twooperations:
 Push (insertion)
 Pop(deletion)
 Before inserting any element in queue we have to check that queue is full or not for
that the condition is rear>=0 and for deleting an element we have to check the queue
is empty or not for that the condition is Front= Null.
 How to enter and delete elements from the queue and see the front and rear pointer
in belowfigure:

0 1 2 3 4 5
10 20 30 40 50

Front Rear
st
1. Delete 1 element from queue for that front=front+1
0 1 2 3 4 5
20 30 40 50

3
COMPUTER ENGINEERING ALGORITHMS

Front Rear
2. Insert element 60 in queue for that rear=rear+1
0 1 2 3 4 5
20 30 40 50 60

Front Rear

 Push/Insertion/Enqueue algorithm:
 For writing an algorithm we can define following terms: S= it is an array having n
elements.
 Rear= pointer to point at last end of queue Front= pointer point to first end of queue
 X= value which want to insert or delete from queue
 Step 1: Start
 Step 2: if rear>= size then
Print “Queue is overflow” go to step 6
 Step 3: Rear = Rear+1
 Step 4: S[Rear] = x
 Step 5: if front=-1 then
Front=0
 Step 6: Exit

 Pop/ Deletion/Dequeue algorithm:


 Step 1: Start
 Step 2: if (front=-1 or front=0) then
Print “queue is underflow” go to step6
 Step 3: X = S[front]
 Step 4: write X
 Step 5: if front=rear
Then Front =0
Rear = 0 else
Front=front+1
 Step 6: Exit.

 Circular Queue:
 Circular queue is a queue in which data are stored in such a way that first element
follows the last element of queue. In circular queue when front and rear point
reaches at the last position then it moves to first position of queue.
 A queue is called circular queue when the last element comes just before 1 st element.

4
COMPUTER ENGINEERING ALGORITHMS

 In this when rear pointer = n and if we try to insert an element then this element
assign to 1st position instead of increasing rear pointer to n+1.
 We reset the rear pointer to 1.
 Similarly, when front pointer = n and if we try to delete an element then we reset the
front pointer to 1 instead of n+1.
 Suppose that queue contains one element that is rear=front and then we remove that
one element then front and rear pointer are now assign to null to indicate that queue
is empty.

 Static implementation of circular queue:


 Insertion Algorithm:
 Step 1: Start
 Step 2: if F=0 and R=N-1
Then print “queue is overflow” and go to step 6
 Step 3: else if F<- -1 and R<- -1
Then F = 0 and R = 0
Q[R] = x
 Step 4: else if R=N-1
then F=0 Then R = 1
Q[R]=x
 Step 5: else R=R+1
Q[R]=x
 Step 6: Finished

 Deletion Algorithm:
 Step 1: start
 Step 2: if F=R=-1Then print “queue is under flow” go to step 7

5
COMPUTER ENGINEERING ALGORITHMS

 Step 3: X= Q[F]
 Step 4: write pop element “X”
 Step 5: if F=R
Then F=-1
R=-1
 Step 6: else if F=size
Then F=0
Else F=F+1
 Step 7: Finished

 Application of Queue:
 Resource Sharing among single level
 In call center
 To control interrupt in Micro processor
 Widely used in simulation work.
 In mailbox application when we save the message to communicate between two
users or process in system is working according to queue.
 In operating system for process scheduling or disk scheduling

3. Time Complexity: Best case, Average case, worst case analysis of algorithms

 An algorithm is said to be capable and speedy, if it takes less time to execute and
consumes less memory space. The performance of an algorithm is measured on the
basis of following properties:

 Time Complexity: it is define as amount of time required to the particular algorithm to


complete the program. For example there are many solutions for any program from that
which is take minimum time to complete the program is the good solution for that
particular problem because it take less time to completion. The time complexity of
algorithms is expressed using the big O notation.

 Space Complexity: it is defined as total amount of space required for particular


program to complete the execution. When memory available is limited and for multi
user system space complexity must taken seriously.

 According to time required for particular algorithm compilation there are three types
for measure for the time complexity.
1. Best case time complexity: it defines as, when particular solution algorithm takes
minimum amount of time for compilation.
2. Average case time complexity: it defined as, when a particular algorithm takes
average amount of time for compilation.

6
COMPUTER ENGINEERING ALGORITHMS

3. Worse case time complexity: it defined as, when solution particular algorithm
takes maximum amount of time for compilation.

3.1. Asymptotic Notations

 When it comes to analysing the complexity of any algorithm in requisites of time


and space, we can never provide for any algorithm that how much the time required
and the space required. In mathematics asymptotic notation is defined for boundation
of run time of any algorithm. Using this notation we can easily find out different
cases of the algorithm like worse case, avg case or best case.
 Example: Running time of one operation is z(n) and for another operation it is
considered as a(n^2). It refers to running time will raise with increase in 'n' for first
operation and running time will enlarge exponentially for second operation.
Similarly the running time of both operations will be same if n is appreciably small.
 According to mathematical boundation there are three types of asymptotic notation
available for finding running time of any algorithm.

3.1.1. Big oh notation(O):it is also called as upper bound. It is used to define upper
bound running time of any algorithm. It is used to measure the worse case of time
complexity. It is graphically represented as follow.

 For ex f(n) and g(n) both are non negative integer functions. then f(n) = O(g(n)) as
f(n) is big oh of g(n) or f(n) is on the order of g(n)) if there exists constants c and no
such that: F(n)≤cg(n) for all n≥no This implies that f(n) does not grow faster than
g(n), or g(n) is an upper bound on the function f(n). for finding time complexity of
any algorithm this notification is most commonly used

3.1.2. Omega notation(Ω): it is also called as lower bound. It is used to define lower
bound running time of any algorithm. It is used to measure the best case of time
complexity means used to measure minimum time required for any algorithm. It is
graphically represented as follow.

7
COMPUTER ENGINEERING ALGORITHMS

 For ex f(n) and g(n) both are non negative integer functions then f(n)=Ω(g(n)) where
there exist positive constants c and n0 such that 0 ≤ cg(n) ≤ f(n) for all n ≥ n0

3.1.3.Theta notation(Ɵ): it is also called as tight bound. It is used to define lower


bound and upper bound running time of any algorithm. It is used to measure the
average case time complexity of anyalgorithm.

 For ex f(n) and g(n) both are non negative integer functions then f(n)=Θ(g(n) where
there exist positive constants c1, c2 and n0 such that 0 ≤ c1g(n) ≤ f(n) ≤ c2g(n) for
all n ≥ n0

3.2. Typical Complexities of an Algorithm


 Constant Complexity: It imposes a complexity of O(1). It undergoes an
execution of a constant number of steps like 1, 5, 10, etc. for solving a given
problem. The count of operations is independent of the input data size.

8
COMPUTER ENGINEERING ALGORITHMS

 Logarithmic Complexity: It imposes a complexity of O(log(N)). It undergoes


the execution of the order of log(N) steps. To perform operations on N
elements, it often takes the logarithmic base as 2. For N = 1,000,000, an
algorithm that has a complexity of O(log(N)) would undergo 20 steps (with a
constant precision). Here, the logarithmic base does not hold a necessary
consequence for the operation count order, so it is usually omitted.
 Linear Complexity: It imposes a complexity of O(N). It encompasses the same
number of steps as that of the total number of elements to implement an
operation on N elements. For example, if there exist 500 elements, then it will
take about 500 steps. Basically, in linear complexity, the number of elements
linearly depends on the number of steps. For example, the number of steps for
N elements can be N/2 or 3*N.
 It also imposes a run time of O(n*log(n)). It undergoes the execution of the
order N*log(N) on N number of elements to solve the given problem.
For a given 1000 elements, the linear complexity will execute 10,000 steps for
solving a given problem.
 Quadratic Complexity: It imposes a complexity of O(n2). For N input data
size, it undergoes the order of N2 count of operations on N number of elements
for solving a given problem. If N = 100, it will endure 10,000 steps. In other
words, whenever the order of operation tends to have a quadratic relation with
the input data size, it results in quadratic complexity. For example, for N
number of elements, the steps are found to be in the order of 3*N 2/2.
 Cubic Complexity: It imposes a complexity of O(n3). For N input data size, it
executes the order of N3 steps on N elements to solve a given problem.
For example, if there exist 100 elements, it is going to execute 1,000,000 steps.
 Exponential Complexity: It imposes a complexity of O(2n), O(N!), O(nk), ….
For N elements, it will execute the order of count of operations that is
exponentially dependable on the input data size. For example, if N = 10, then
the exponential function 2N will result in 1024. Similarly, if N = 20, it will
result in 1048 576, and if N = 100, it will result in a number having 30 digits.
The exponential function N! grows even faster; for example, if N = 5 will result
in 120. Likewise, if N = 10, it will result in 3,628,800 and so on.

9
COMPUTER ENGINEERING ALGORITHMS

3.3. How to approximate the time taken by the Algorithm?


 So, to find it out, we shall first understand the types of the algorithm we have.
There are two types of algorithms:
1. Iterative Algorithm: In the iterative approach, the function repeatedly runs
until the condition is met or it fails. It involves the looping construct.
2. Recursive Algorithm: In the recursive approach, the function calls itself until
the condition is met. It integrates the branching structure.
 However, it is worth noting that any program that is written in iteration could be
written as recursion. Likewise, a recursive program can be converted to
iteration, making both of these algorithms equivalent to each other.
 But to analyze the iterative program, we have to count the number of times the
loop is going to execute, whereas in the recursive program, we use recursive
equations, i.e., we write a function of F(n) in terms of F(n/2).
 Suppose the program is neither iterative nor recursive. In that case, it can be
concluded that there is no dependency of the running time on the input data
size, i.e., whatever is the input size, the running time is going to be a constant
value. Thus, for such programs, the complexity will be O(1).

1. For Iterative Programs


 Consider the following programs that are written in simple English and does not
correspond to any syntax.
 Example1:
 In the first example, we have an integer i and a for loop running from i equals 1
to n. Now the question arises, how many times does the name get printed?
A()
{
int i;
for (i=1 to n)
printf("Edward");
}
 Since i equals 1 to n, so the above program will print Edward, n number of
times. Thus, the complexity will be O(n).
 Example2:
A()
{

10
COMPUTER ENGINEERING ALGORITHMS

int i, j:
for (i=1 to n)
for (j=1 to n)
printf("Edward");
}
 In this case, firstly, the outer loop will run n times, such that for each time, the
inner loop will also run n times. Thus, the time complexity will be O(n2)
 Example3:
A()
{
i = 1; S = 1;
while (S<=n)
{
i++;
S = S + i;
printf("Edward");
} }
 As we can see from the above example, we have two variables; i, S and then we
have while S<=n, which means S will start at 1, and the entire loop will stop
whenever S value reaches a point where S becomes greater than n.
 Here i is incrementing in steps of one, and S will increment by the value of i,
i.e., the increment in i is linear. However, the increment in S depends on the i.
 Initially;
 i=1, S=1
 After 1st iteration;
 i=2, S=3
 After 2nd iteration;
 i=3, S=6
 After 3rd iteration;
 i=4, S=10 … and so on.
 Since we don't know the value of n, so let's suppose it to be k. Now, if we notice
the value of S in the above case is increasing; for i=1, S=1; i=2, S=3; i=3, S=6;
i=4, S=10; …

11
COMPUTER ENGINEERING ALGORITHMS

 Thus, it is nothing but a series of the sum of first n natural numbers, i.e., by the
time i reaches k, the value of S will be k(k+1)/2.

 To stop the loop, has to be greater than n, and when we solve this

equation, we will get > n. Hence, it can be concluded that we get a


complexity of O(√n) in this case.

2. For Recursive Program


 Consider the following recursive programs.
 Example1:
A(n)
{
if (n>1)
return (A(n-1))
}
 Solution;
 Here we will see the simple Back Substitution method to solve the above
problem.
 T(n) = 1 + T(n-1) …Eqn. (1)
 Step1: Substitute n-1 at the place of n in Eqn. (1)
T(n-1) = 1 + T(n-2) ...Eqn. (2)
 Step2: Substitute n-2 at the place of n in Eqn. (1)
T(n-2) = 1 + T(n-3) …Eqn. (3)
 Step3: Substitute Eqn. (2) in Eqn. (1)
T(n)= 1 + 1+ T(n-2) = 2 + T(n-2) …Eqn. (4)
 Step4: Substitute eqn. (3) in Eqn. (4)
T(n) = 2 + 1 + T(n-3) = 3 + T(n-3) = …... = k + T(n-k) …Eqn. (5)
 Now, according to Eqn. (1), i.e. T(n) = 1 + T(n-1), the algorithm will run until
n>1. Basically, n will start from a very large number, and it will decrease
gradually. So, when T(n) = 1, the algorithm eventually stops, and such a
terminating condition is called anchor condition, base condition or stopping
condition.
 Thus, for k = n-1, the T(n) will become.
 Step5: Substitute k = n-1 in eqn. (5)

12
COMPUTER ENGINEERING ALGORITHMS

T(n) = (n-1) + T(n-(n-1)) = (n-1) + T(1) = n-1+1


 Hence, T(n) = n or O(n).

3.4. Recurrence Relation


 A recurrence is an equation or inequality that describes a function in terms of its
values on smaller inputs. To solve a Recurrence Relation means to obtain a
function defined on the natural numbers that satisfy the recurrence.
 For Example, the Worst Case Running Time T(n) of the MERGE SORT
Procedures is described by the recurrence.
 T (n) = θ (1) if n=1

 2T + θ (n) if n>1
 There are three methods for solving Recurrence:
1. Substitution Method
2. Recursion Tree Method
3. Master Method

1. Substitution Method:
 The Substitution Method Consists of two main steps:
 use the Solution.
 Use the mathematical induction to find the boundary condition and shows that
the guess is correct.
 For Example1 Solve the equation by Substitution Method.

 T (n) = T +n
 We have to show that it is asymptotically bound by O (log n).
 Solution:
 For T (n) = O (log n)For T (n) = O (log n)
 We have to show that for some constant c
 T (n) ≤c logn.
 Put this in given Recurrence Equation.

 T (n) ≤c log +1

≤c log + 1 = c logn-clog2 2+1


≤c logn for c≥1
Thus T (n) =O logn.
 Example2 Consider the Recurrence

13
COMPUTER ENGINEERING ALGORITHMS

 T (n) = 2T + n n>1
 Find an Asymptotic bound on T.
 We guess the solution is O (n (logn)).Thus for constant 'c'.
 T (n) ≤c n logn
 Put this in given Recurrence Equation.
 Now,

 T (n) ≤2c log +n


≤cnlogn-cnlog2+n

=cn logn-n (clog2-1)

≤cn logn for (c≥1)

Thus T (n) = O (n logn).

1. Forward substitution method:


 One of the simplest methods for solving simple recurrence relations is using
forward substitution. In this method, we solve the recurrence relation
for n=0,1,2,…n=0,1,2,… until we see a pattern. Then we make a guesswork and
predict the running time. The final and important step in this method is we need
to verify that our guesswork is correct by using the induction. Consider a
recurrence relation
 Example: T(n)=1 if n=1
=T(n−1)+1 otherwise
 Solution: We can calculate the running time for n=0,1,2,.. as follows

n T(n)

1 1

2 T(2)=T(2−1)+1=1+1=2

3 T(3)=T(3−1)+1=1+1+1=3

4 T(4)=T(4−1)+1=1+1+1+1=4

 We can easily see the pattern here. When the value of n=kn=k, T(n)=kT(n)=k.
So the running time is
T(n)=n

14
COMPUTER ENGINEERING ALGORITHMS

 We need to verify that the running time we guessed is correct by induction (not
mathematical induction ;)). Since T(n)=nT(n)=n, we can clearly see
that T(1)=1,T(2)=2,T(3)=3,…T(1)=1,T(2)=2,T(3)=3,….

 Example: T(n)=0 if n=0


=T(n−1)+n otherwise
 Solution: We can calculate the running time for n=0,1,2,.. as follows

n T(n)

1 T(1)=T(1-1)+1=T(0)+1=0+1=1

2 T(2)=T(2−1)+2=T(1)+2=1+2=3

3 T(3)=T(3−1)+3=T(2)+3=3+3=6

4 T(4)=T(4−1)+4=T(3)+4=6+4=10

 By observing above generated equation we can derived formula


 T(n)=n(n+1)/2
=n2 /2+n/2
 So we denote T(n) in terms of big oh notation as T(n)=O(n2)

2. Backward substitution method:


 In forward substitution method, we put n=0,1,2,…n=0,1,2,… in the recurrence
relation until we see a pattern. In backward substitution, we do the opposite i.e.
we put n=n, n−1,n−2 ,… or n=n, n/2, n/4,… until we see the pattern. After we
see the pattern, we make a guesswork for the running time and we verify the
guesswork.
 Example: T(n)=0 if n=0
=T(n−1)+n otherwise ……. Eq(1)
 Solution: now put n=n-1 in eq (1)
T(n-1)= T(n-1-1)+(n-1) =T(n-2)+(n-1) ……… eq(2)
Putting eq(2) in eq(1) we get
T(n)= T(n-2)+(n-1)+n ………..eq(3)
Now take n=n-2 in eq (1)
T(n-2)=T(n-2-1)+(n-2) =T(n-3)+(n-2) ……… eq(4)

15
COMPUTER ENGINEERING ALGORITHMS

Now put eq (4) in eq (3) we get


T(n)=T(n-3)+(n-2)+(n-1)+n
Now put k=3 so we get
T(n)=T(n-k)+(n-k+1)+(n-k+2)+…….. +n
Now if k=n then
T(n) =T(k-k)+(k-k+1)+(k-k+2)+…….. +n
=T(0)+1+2+……..+n
=0+1+2+…… +n
=n(n+1)/2=n2/2+n/2
 So we denote T(n) in terms of big oh notation as T(n)=O(n2)

2. Master method:
 The master theorem is a formula for solving recurrences of the form T(n) =
aT(n/b)+f(n), where a>=1 and b > 1 and f(n) is asymptotically positive.
(Asymptotically positive means that the function is positive for all su_ciently
large n.)
 This recurrence describes an algorithm that divides a problem of size n into a
subproblems, each of size n=b, and solves them recursively.
 Master’s theorem solves recurrence relations of the form-

 Here, a >= 1, b > 1, k >= 0 and p is a real number.


 Master Theorem Cases-
 To solve recurrence relations using Master’s theorem, we compare a with b K.
 Then, we follow the following cases-
 Case-01:
If a > bK, then T(n) = θ (nlogba)
 Case-02:
If a = bk and
If p < -1, then T(n) = θ (nlogba)
If p = -1, then T(n) = θ (nlogba log2n)
If p > -1, then T(n) = θ(nlogba logp+1n)
 Case-03:
If a < bk and
If p < 0, then T(n) = O (nk)
If p >= 0, then T(n) = θ (nklogpn)

16
COMPUTER ENGINEERING ALGORITHMS

 Example: Solve the following recurrence relation using Master’s theorem-T(n)


= 3T(n/2) + n2
 Soluton: We compare the given recurrence relation with
T(n) = aT(n/b) + θ (nk logpn).
Then, we have-
a=3
b=2
k=2
p=0
Now, a = 3 and bk = 22 = 4.
Clearly, a < bk.
So, we follow case-03.
Since p = 0, so we have-
T(n) = θ (nk logpn)
T(n) = θ (n2 log0n)
So, T(n)= θ (n2)
 Example: Solve the following recurrence relation using Master’ theorem-
T(n) = 2T(n/2) + nlogn
 Solution: We compare the given recurrence relation with
T(n) = aT(n/b) + θ (nk logpn).
Then, we have-
a=2
b=2
k=1
p=1
Now, a = 2 and bk = 21 = 2.
Clearly, a = bk.
So, we follow case-02.
Since p = 1, it is p>-1 so we have-
T(n) = θ(nlogba logp+1n)
T(n) = θ(nlog22 log1+1n)
Thus, T(n)= θ(nlog2n)
 Example: Solve the following recurrence relation using Master’s theorem-
T(n) = 2T(n/4) + n0.51
 Solution: We compare the given recurrence relation with
T(n) = aT(n/b) + θ (nk logpn).
Then, we have-
a=2
b=4
k = 0.51

17
COMPUTER ENGINEERING ALGORITHMS

p=0
Now, a = 2 and bk = 40.51 = 2.0279.
Clearly, a < bk.
So, we follow case-03.
Since p = 0, so we have-
T(n) = θ (nk logpn)
T(n) = θ (n0.51log0n)
So, T(n)= θ (n0.51)

 Example: Solve the following recurrence relation using Master’s theorem-


T(n) = √2T(n/2) + logn
 Solution: We compare the given recurrence relation with
T(n) = aT(n/b) + θ (nk logpn).
Then, we have-
a = √2
b=2
k=0
p=1
Now, a = √2 = 1.414 and bk = 20 = 1.
Clearly, a > bk.
So, we follow case-01.
So, we have-
T(n) = θ (nlogba)
T(n) = θ (nlog2√2)
T(n) = θ (n1/2)
 Example: Solve the following recurrence relation using Master’s theorem-
T(n) = 8T(n/4) – n2logn
 Solution: The given recurrence relation does not correspond to the general form
of Master’s theorem. So, it can not be solved using Master’s theorem.
 Example: Solve the following recurrence relation using Master’s theorem-
T(n) = T(n) = 3T(n/3) + n/2
 Solution: We write the given recurrence relation as T(n) = 3T(n/3) + n.
 This is because in the general form, we have θ for function f(n) which hides
constants in it.
 Now, we can easily apply Master’s theorem.
 We compare the given recurrence relation with T(n) = aT(n/b) + θ (nk logpn).
 Then, we have-
 a=3
 b=3
 k=1
 p=0

18
COMPUTER ENGINEERING ALGORITHMS

 Now, a = 3 and bk = 31 = 3.
 Clearly, a = bk.
 So, we follow case-02.
 Since p = 0, so we have-
 T(n) = T(n) = θ(nlogba logp+1n)
 T(n) = T(n) = θ(nlog33 log0+1n)
 So, T(n) = θ (nlogn)

3. Recursion Tree Method:


 Recursion Tree Method is a pictorial representation of an iteration method
which is in the form of a tree where at each level nodes are expanded.
 In general, we consider the second term in recurrence as root.
 It is useful when the divide & Conquer algorithm is used.
 It is sometimes difficult to come up with a good guess. In Recursion tree, each
root and child represents the cost of a single subproblem.
 We sum the costs within each of the levels of the tree to obtain a set of pre-level
costs and then sum all pre-level costs to determine the total cost of all levels of
the recursion.
 A Recursion Tree is best used to generate a good guess, which can be verified
by the Substitution Method.

 Example 1: Consider T (n) = 2T + n2


 We have to obtain the asymptotic bound using recursion tree method.
 Solution: The Recursion tree for the above recurrence is

19
COMPUTER ENGINEERING ALGORITHMS

4. Introduction for string

 String: String is defined as a sequence of characters or group of character. In terms


of c language string is an array of characters.
 While storing the string in character array, the size of the array must be one more
then the size of the string. Because the last character in the string is ‘\0’ or NULL.
 The string terminated with NULL or ‘\0’ is known as null terminated string.
 For example: To store “HELLO” in array the array must be declared as char a[6].
 For example:
String “HELLO” is stored as shown in fig

H E L L O \0
 String Character set: A string is a set of alphabets (Upper case:A-Z, Lower case:a-
z), Numeric value (0-9) and special characters like +, -, *, %, /, (, ), [, ], {, }, $, # &,
,, ., ?, etc, or combination of any of three.

 Static Representation of String:


 Static string can’t be changed throughout the program. You have to assign value at
the compile time. i.e. at the time when you write the program.
 char name[10]= “COMPUTER”;
OR
 char name[10]={ ‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’,’E’,’R’,’\0’};
 The memory representation of this string is as,
C O M P U T E R \0 -
 Dynamic Representation of String:
 In dynamic representation of string you have to assign value at the run time. i.e. at
the time when your program is executed. By using input function like gets(), scanf().
 For Dynamic allocation we use,

20
COMPUTER ENGINEERING ALGORITHMS

 gets(string name); OR scanf(“%s”, string name);


 Example:
gets(name); OR scanf(“%s”,name);
 Reading and Writing String
 Reading/Input Operation:
 In this operation you have to enter string from keyboard. For reading operation you
have to use following two function.
1. gets ():
Syntax:
gets(String_name); //Enter string including white_space.
Example:
gets (hello world);
2. scanf ():
Syntax:
scanf (“%s”, String_name); //Enter string excluding white_space.
Example:
scanf(“%s”, hello_world); //Right
scanf(“%s”, helloworld); //Right
scanf(“%s”, hello world); //Wrong

 Writing/Output Operation:
 In this operation you get an output on screen after execution. For writing an
operation you have to use following two function.
1. puts ():
Syntax:
puts(string_name);
Example:
puts (hello world);
Output:
hello world

2. printf():
Syntax:
printf (“%s”, string_name);
Example:
printf (“%s”, hello world);
Output:
hello

5. Types of string Operation.

21
COMPUTER ENGINEERING ALGORITHMS

1. String length: The function returns the length of the string, not counting the null
character at the end. That is, it returns the character count of the string, without
the terminator.

Algorithm:
Step 1: [initialization]
count=0 [ Read String & increment counter]
Step 2: while (str[count]! = Null)
count=count+1
Step 3: write (length is count)
Step 4: [Finished]
Exit

Program:
#include <stdio.h>
#include <conio.h>
void main ()
{
int Count=0; char str [10];
printf("Enter The
String:"); scanf("%s",str);
while(str[Count]!='\0')
{
Count ++;
}
printf("%d", Count);
getch();
}

Output:
Enter string : hello
5

2. String copy: This function is used to copy from one string to another. Suppose
we have two string s1 and s2, then if we want to copy s2 into s1 we required copy
function.
S1= blank or null
S2=”computer”
Strcpy(s1,s2) will copy s2 into s1.

22
COMPUTER ENGINEERING ALGORITHMS

Algorithm:
strcpy (s1, s2)
Step 1: [initialization]
S1<-””
S2<-”Hello”
I<-0, j<-0
Step 2: while (S2[i]!=’\0’)
S1[j]<-S2[i]
i<-i+1
j<-j+1
Step 3: Print string S1
Step 4: [Finished]
Exit

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20]="";
char str2[20] = "Hello";
int i=0, j=0;
while(str2[i]!='\0')
{
str1[j] = str2[i];
i++; j++;
}
printf("Copy string is: %s", str1);
getch();
}
Output:
Copy string is: Hello

3. String Concatenation: This function is used to join two strings. Suppose we


have two string s1 and s2 then concate that s1 and s2 as one string we use this
operation.
S1= “hi’
S2= “hello”
Then concatenation of string is “hihello”

23
COMPUTER ENGINEERING ALGORITHMS

Algorithm:
Step 1: [initialization]
Set Str3<- Null
I<-0, J<-0, K<-0
Read the string str1, str2.
Step 2: repeat step 2 until condition is false
while (I! = strlen(str1))
set Str3[K]<-str1 [I]
set K<-K+1
set I<-I+1
Step 3: repeat step 3 until condition is false
while(J! = strlen(str2))
set Str3[K]<- str2[J]
set J<-J+1
set K<-K+1
Step 4: print str3
Step 5: [Finished]
Exit

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[10],str2[10],str3[25];
int i=0, j=0, k=0;
printf("Enter the First string:");
scanf("%s",str1);
printf("Enter the Second string:");
scanf("%s",str2);
while(i!=strlen(str1))
{
str3[k]=str1[i];
i++;
k++;
}
while(j!=strlen(str2))
{
str3[k]=str2[j];

24
COMPUTER ENGINEERING ALGORITHMS

j++;
k++;
}
printf("The join string is: %s", str3);
getch();
}
Output:
Enter the First string: Parul
Enter the Second string: University
The join string is: ParulUniversity

4. String Compare: This is use to compare both the string on the basis of length. If
we have two string s1 and s2 then compare both character by character , if both
are equal then print string are equal and not then print strings are not equal.
S1= “hello”
S2= “hello”
Strings are equal

Algorithm:
Step 1: [initialization]
i=0
same=0
len1=0
len2=0
Step 2: [read two string]
Read (str1)
Read (str2)
Step 3: set len1=strlen(str1)
Step 4: set len2=strlen(str2)
Step 5: if len1=len2
Step 6: While i<len1
if str1[i]=str2[i]
i=i+1
else
break
if i=len1
print both strings are same
Step 7 : if len1!=len2
print both strings are not same
Step 8 : check same=0
Step 9 : write Both the string are not equal
25
COMPUTER ENGINEERING ALGORITHMS

Step 10: [finished]


Exit

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
printf("Enter first string: ");
scanf("%s",str1);
printf("Enter second string: ");
scanf("%s",str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
{
while(i<len1)
{
if(str1[i]==str2[i]) i++;
else break;
}
if(i==len1)
{
same=1;
printf("Both the strings are equal");
}
}
if(len1!=len2)
{
printf("Both the strings are not equal");
}
if(same==0)
{
printf("Both the strings are not equal");
}
return 0;
}

26
COMPUTER ENGINEERING ALGORITHMS

Output:
Enter first string: Parul
Enter second string: Parul
Both the strings are equal

5. String Reverse: This function is used to reverse the given string. Reversing string
means print existing string from last character to 1st character. For that assuming
that
String1= original string
String2= reverse of original
Reverse(string1, string2)

Algorithm:
Step1: [initialization]
i<-0
j<-0
temp
Step2: read str
Step3: set j<-strlen(str)-1
Step4: repeat step 5 while i<j
Step5: temp<-str[i]
str[i]<-str[j]
str[j]<-temp
i<-i+1
j<-j-1
[End of loop]
Step 6: write(str)
Step 7: [finished]
Exit

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10], temp;
int i=0, j=0;
printf("Enter the string:");

27
COMPUTER ENGINEERING ALGORITHMS

scanf("%s",str);
i=0;
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string is: %s",str);
getch();
}

Output:
Enter the string: Parul
Reverse string is: luraP

6. Substring: This function is used to find sub string from the main string from
specific position.
For finding a substring from a string we must specify a string character position
and no of character of a string.
Example: s1=”computer”
Cursor: starting position of substring
Num= no of character of substring
A substring function substr(s1,cursor,num). suppose we have cursor=4 and num=3
then substr(s1,4,3)=”put”

Algorithm: input (str, cursor,num)


Step 1: [initialization]
set i<-position
set j<-0
Step 2: repeat step 3 to 6
while str[i]!=NULL and length >0
Step 3: set substr[j]<-str[i]
Step 4: set i=i+1
Step 5: set j=j+1;
Step 6: set length=length-1

[End of while loop]

28
COMPUTER ENGINEERING ALGORITHMS

Step 7: set substr[j]=NULL


Step 8 : write substr
Exit

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],substr[50];
int pos,length,i=0,j=0;
printf("Enter the main string: ");
scanf("%s",str);
printf("\nEnter the position from which to start the substring: ");
scanf("%d",&pos);
printf("\nEnter the length of the substring: ");
scanf("%d",&length);
i=pos;
while(str[i]!='\0' && length>0)
{
substr[j]=str[i];
i++;
j++;
length--;
}
substr[j]='\0';
printf("\nThe substring is: %s", substr);
getch();
}

Output:
Enter the main string: Gujarat Technological University
Enter the position from which to start the substring: 8
Enter the length of the substring: 13
The substring is: Technological

7. Converting Characters of a string into upper case and lower case: This
function is used to convert given string into upper case and lower case. The ASCII
code for A-Z varies from 65-90 and the ASCII code for a-z ranges from 97-122.

29
COMPUTER ENGINEERING ALGORITHMS

So, if we have to convert lower case character into upper case, we just need to
substract 32 from the ASCII value of the character. And if we have to convert an
upper case character into lower case, we need to add 32 to the ASCII value of the
character.

Algorithm: To upper case


Step 1: [initialization]
Set i<-0
Step 2: repeat step 3 while str[i]! = NULL
Step 3: if (str[i] >=’a’ and str[i] <= ‘z’)
Set str[i]=str[i]-32 [end of if]
Set i=i+1
[End of while loop]
Step 4: [print the upper case string]
Write str
Step 5: [finished]
Exit

Algorithm: To lower case


Step 1: [initialization]
Set i<-0
Step 2: repeat step 3 while str[i]! = NULL
Step 3: if (str[i]>=’A’ and str[i] <=’Z’)
str[i] = str[i]+32 [end of if]
set i=i+1
[end of while loop]
Step 4: [write the lower case string]
write str
Step 5: [finished]
Exit

Program: To upper case


#include<stdio.h>
#include<conio.h>
void main()
{
char str [50];
int i=0;
printf("\nEnter a string: ");
scanf("%s", str);
while(str[i]!='\0')

30
COMPUTER ENGINEERING ALGORITHMS

{
if(str[i]>='a' && str[i]<='z')
str[i]=str[i]-32;
i++;
}
printf("\nUpper case string is= %s", str);
getch();
}

Output:
Enter string: parul
Upper case string is= PARUL

Program: To lower case


#include <stdio.h>
#include <conio.h>
void main ()
{
char str[100];
int i=0;
printf("\n Enter a string: ");
scanf("%s",str);
while(str[i]!='\0')
{
if(str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32;
i++;
}
printf("\n Lower case String is = %s", str);
getch ();
}

Output:
Enter string: PARUL
Lower case String is = parul

8. String insertion: if we want to insert substring at some position, we required


function insertion(s1, position, substring)
Example: suppose we have string s1=”: my name xyz” and we have to insert sub
string”is” at position 8 then insertion(s1,8,”is”)

31
COMPUTER ENGINEERING ALGORITHMS

Output: my name is xyz


Algorithm: insertion(text, position, string)
Step1: [initialization]
Set i<-0
Set j<-0
Set l<-0
Step2: [to reach at position for insert]
Repeat while(i!=position)
Temp[i]=text[i]
i<-i+1
Step3: [to store position in m]
M<-i+1
Step4: [insert string at position]
Repeat while(j!=len(string))
Temp[i]=string[j]
i<-i+1
j<-j+1
Step5: [to find rest of character after string position]
l<- len(text)-position
Step6: [insert rest of character after inserting string]
Repeat while(l!=0)
Temp[i]=text[m]
i<-i+1
m<-m+1
l<-l-1
Step7: [finished]
Exit

9. String deletion: if we want to delete substring at some position, we required


function deletion(s1, position, length)
Example: suppose we have string s1=”computer science and engg. “
Position=13(starting position of word)
Length=3(no of character to delete)
Delete(s1,position,length)
Output: computer scienand engg
Algorithm: delete(text, position, length)
Step1: [initialization]
Set i<-0
Set j<-Length
Set k<-0

32
COMPUTER ENGINEERING ALGORITHMS

Step2: [to reach at position for deletion]


Repeat while(i!=position)
Temp[k]=text[j]
i<-i+1
k<-k+1
Step3: [to find new position after delete a string]
i<-(position+length)
Step4: [to find position of rest of character after deleting string]
j<- len(text)-i+1
Step5: [insert rest of character after inserting string]
Repeat while(j!=0)
Temp[k]=text[i]
k<-k+1
j<-j-1
i<-i+1
Step6: [finished]

10. String appending: it means we add new string at the end of existing string.
For appendimg string
Text=original string
String= word or noew string which is append in original
Append(text,string)
Algorithm: Append(text,string)
Step1: [initialization]
Set i<-0
Set j<-0
Step2: [to reach end of string]
Repeat while(i!=len(string))
i<-i+1
Step3: [appending string]
Repeat while(j!=len(string))
Text[i]<-string[j]
i<-i+1
j<-j+1
Step4: [print string after appending]
Write(text)
Step5: [finished]

33

You might also like