Algorithm ch-2
Algorithm ch-2
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
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
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.
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:
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.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
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
8
COMPUTER ENGINEERING ALGORITHMS
9
COMPUTER ENGINEERING ALGORITHMS
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
12
COMPUTER ENGINEERING ALGORITHMS
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
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,
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,….
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
15
COMPUTER ENGINEERING ALGORITHMS
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-
16
COMPUTER ENGINEERING ALGORITHMS
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)
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)
19
COMPUTER ENGINEERING ALGORITHMS
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.
20
COMPUTER ENGINEERING ALGORITHMS
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
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
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
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”
28
COMPUTER ENGINEERING ALGORITHMS
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.
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
Output:
Enter string: PARUL
Lower case String is = parul
31
COMPUTER ENGINEERING ALGORITHMS
32
COMPUTER ENGINEERING ALGORITHMS
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