Beruflich Dokumente
Kultur Dokumente
Iterative::-
Introduction to List
List is a linear data structure.
List:- A group of elements referenced with a single name ,consisting of same type with
variable no. of elements is called as a List
List operations:I
Find ,Insert ,Delete ,Update ,Merge ,Split ,Append/Concatinate.
ex: Telephone Directory
0
5
1
9
2
13
size-1
16
24
33
45
Algorithm Analysis
When several algorithms are available,the best algorithm is to be selected.
Hence the algorithm is to be analysed.
Resources Required:- Input/output Devises
Memory
CPU Time
Space Complexity:-Estimation of the extra memory locations required for the algorithm.
Time Complexity:- Estimation of the time required for executing the algorithm.
if there are two positive constants C and n0 such that T(N) C f(N)
When
N no
T(N) =(g(N))
when N no
i f there are two positive constants C and n0 such that T(N) C g(n)
Rule3:- If logk n = O(n) for any constant k.This tells us that logarithms grow very
slowly.
Function
Name
Constant
Logn
Logarithmic
Log2n
Log-squared
Linear
nlogn
n2
Quadratic
n3
Cubic
2n
Exponential
General rules: The running time of a for loop is at most the running time of the statements inside
the for loop(including tests) times the no of iterations.
The total running time of a statement inside a group of nested loops is the running
time of the statement multiplied by the product of the sizes of all the for loops.
The running time of an if /else statement is never more than the running time of
the test plus the larger of the running times of s1 and s2.
Euclids Algorithm for computing GCD is if M > N, then M mod N < M/2.
Time Complexity:Best Case:- Element may exist in the first place T(n) = O(1) i.e for loop is executing
only once.
Worst Case:- When the element is not existing the for loop/Basic operation is
executed n times
T(n) = O(n).
0 1
2 5
2
n-1
16
22
34
39
43
P
s-1
x=19
1
8
2 n-1
13 16 21 30 35
b0
5
1
11
2
15
3
18
4m-1
20 40 45
2
8
3
11
4 m+n -1
. ..
c 0 1
2
5
s-1
..
s-1
Reading a list
void readlist(int a[],int n)
{ /* reading a list */
int i ;
for(i = 0 ;i< n; i++)
{
printf(Enter the element:%d ,i++);
scanf(%d,&a[i]);
}
}
Printing a list
void printlist(int a[],int n)
{ /* displaying a list */
int i;
for(i=0 ;i< n;i++)
printf(%4d,a[i]);
}
Interactive menu driven program to implement all the list operations . * a is the
mainlist.
# include<stdio.h>
#define s 100
int n,m,l;
main()
{ /* program to implement all the list operations */
int a[s],b[s],c[s],p,x,y,choice;char c;
/* Farward declarations of all functions */
printf(Enter the no of elements of mainlist);
scanf(%d,&n);
readlist(a,n);
while(1)
{
printf(Enter your choice:\n);
printf(1.For find, 2.For Insert, 3.For Delete \n);
printf(4.For Update, 5.For Merge,6.For Split \n);
printf(7.For Append, 8.For Display, 9.For Quit \n);
scanf(%d, &Choice);
switch(choice)
{
case 1:printf(Enter the value to be searched \n);
scanf(%d,&x);
p = find(a,x);
if(p= = -1)
printf(%d is not existing \n,x);
else
printf(%d is existing in position: %d\n, x,p);
break;
case 2:printf(Enter the element to be inserted\n);
scanf(%d,&x);
insert(a ,x);
break;
case 3:printf(Enter the element to be deleted\n);
scanf(%d,&x);
delete(a,x);
break;
case 4:printf(Enter the elements x,y:\n);
scanf(%d %d, &x ,&y);
update(a,x,y);
break;
case 5:printf(Enter the no of elements of second list\n);
scanf(%d,&m);
readlist(b,m);
smerge(a,b,c);
break;
case 6:printf(Enter the element x \n);
scanf(%d, &x);
split(a,b,c);
break;
case7: printf(Enter the no of elements of second list\n);
scanf(%d,&m);
readlist(b,m);
append(a,b,c);
break;
case8: printf(Enter the list to be displayed:a,b,c);
scanf(%c,&c);
switch(c)
{
case a :printlist(a,n);break;
case b :printlist(b,m);break;
case c :printlist(c,l); break;
}
break;
case 9: exit(0);
default: Printf(Enter your code correctly\n);
}
}
}
Sorting
Arranging the elements in some order(ascending/descending) is known as Sorting.
Selection Sort
Time Complexity
Best Case: O(n2)
Worst Case:O(n2)
Average Case:O(n2)
Space Complexity: 1(inplace)
}
Time complexity:
T(n) = n-1+n-2+. + 3+2+1
= n(n-1)
= n2- n
Bubble Sort
Time Complexity:Tbc(n) = O(n) ,Twc(n) = O(n2), Tavg(n) = O(n2)
Space Complexity:Space Complexity: 1(inplace)
void bubblesort(int a[], int n)
{
}
Best Case:- only inner for loop is executed n times
T(n) = O(n)
Worst Case:- T(n) = n-1+n-2 +......... +3+ 2+1
= n(n-1)
= n2-n
= O(n2 )
Insertion Sort
Time complexity: Tbc = O(n), Twc(n) = O(n2), Tavg = O(n2)
Space Complexity : one extra location.
It consists of n-1 passes For pass p =1 through n-1,insertion sort ensures that the elements
in position O through p are in sorted order.Insertion sort makes use of the fact that
elements in position O through p-1 are already known to be in sorted order.
a 0
20
1
80
2
11
n-1
37
95
15
44
A lower bound for Simple Sorting Algorithms:An inversion in an array of numbers is any ordered pair(a(i),a(j)) having the property
that i< j but a[i] > a[j].
The average no of inversions in an array of n distinct numbers is n(n-1)/4
Any algorithm that sorts by exchanging adjacent elements requires (n2) time on average
Shell Sort
Shell sort :- (Donald Shell). One of the first algorithms to break the quadratic time
barrier.
It works by comparing elements that are distant.
The distance between comparisons decreases as the algorithms runs until the last phase,
in which adjacent elements are compared.
Sometimes it is referred to as diminishing increment sort.
Shellsort uses a sequence,h1,h2..ht called the increment sequence.After a phase,using
some increment hk , for every i , we have A[i] A[ i + hk] .All the elements spaced hk
apart are sorted .The file is then said to be hk sorted.
Shells increment sequence:- ht = n/2 hk =[hk+1/2 ]. TWC(n) =(n2)
Hibbards increment sequence:- 1, 3, 7, 2k - 1 TWC(n) =(n3/2), Tavg(n) =(n3/2),
Sedgewicks increment sequence:- 1,5, 19, 41, 109 TWC(n) =O(n 4/3)
9.4i 9.2i + 1 or 4i 3.2i + 1 Tavg(n) =O(n 7/6)
Merge Sort
Space Complexity is n and Time Complexity is O(n log2 n).
The fundamental operation in this algorithm is merging two sorted lists.
If n =1, there is only one element to sort and the list is sorted.Otherwise, recursively sort
the first half and the second half.
It gives two sorted halves, which can then be merged together using the merging
algorithm.
This algorithm is a classic divide-and-conquer strategy.
The problem is divided into smaller problems and solved recursively.
The conquering phase consisting of patching together the answers.
Time Complexity:T(1) = 1;
T(n) = 2T(n/2)+n;
T(n/2)
n/2
:
:
= T(n/4) +1
n/4
:
:
T(n/4) = T(n/8)+ 1
n/4
n/8
T(2)/2 = T(1)/1+1
T(n)/n = 1+log2n
T(n) = O(nlog2n)
Quicksort
Space Complexity:- 1
T(n)wc = O(n2)
Tavg(n) = Twc(n) = O(nlog2n)
It is the fastest known algorithm in practice.
Quicksort is a divide-conquer recursive algorithm.
The basic algorithm to sort an array a consists of the following four easy steps:
3.Partition a- {v}(the remaining elements in s) into two disjoint groups . a1 = {X a{ v}| x v } and a2 = { x a {v} | x v }
}
temp = a[lb];
a[lb] = a[j];
a[j] = temp;
qsort(a, lb, j-1);
qsort(a, j+1, rb);
}
}
Time Complexity :- T(n) = T(i) + T(N-i-1) + cn
i is the no of elements in list a1.
Worst Case :- i =0
T(n) = T(0) + T(n-1) +cn
= T(n-1) +cn
T(n-1) = T(n-2) + c(n-1)
T(n-2) = T(n-3) + c(n-2)
;. :
T(3) = T(2) + c. 3
T(2) = T(1) + c.2
n
T(n) = T(1) + c. i = O(n2)
i =2
Best Case:- i =n/2
T(n) = 2T(n/2)+cn
T(n) = T(n/2) + c
n
n/2
Similar to that of merge sort
T(n) = O(nlog 2 n)
n-1
1/ n
T(j)
j=0
Average Case:n-1
T(n)= 2/n
T(j) +c .n
j=0
n-1
T(j) +c .n2
n.T(n) = 2
------I
j=0
n-2
(n-1) T(n-1) = 2 T(j) +c .n-1 2 ----II
j=0
I-II
T(n-1)
= T(n-2) + 2c
n+1
n-1
n +1
T(n-1)
= T(n-2) + 2c
n-1
= T(n-3) + 2c
T(n-2)
n
n-1
n-1
.....
T(2)
= T( 1) +
n-2
2c
3
n+1
T(n)
T(1) + 2c i/1
n+1
T(n) =
n+1
O(log2n)
i=3
n+1
[ . . = loge(n+1) + r- 3 ]
2
Radix Sort
SpaceComplexity : 10n
84
94
74
--4
73
23
--3
42
--2
65
--5
57
--- --6 7
--- --8
9
23
--2
30
--3
65
42 57 61
--- --- --4
5
6
74
73
--7
84
81 94
--- --8
9
11,23,30, 42, 57, 61, 65, 73, 74, 81, 84, 94 is the Final Sorted List.
To reduce the Space Complexity Radix Sort can be implemented using Linked List.
Each pocket is a Queue.
N is the no of records, M is the no of digits.
Radix Sort(First, n]
1.[Perform Sort]
Repeat through step4 for J = 1, 2,,..M.
2.[Initialize the pass]
Repeat for i = 0, 1, 2,..9.
T[I] = B[I] = Null.
3.[Distribute each record in the appropriate pocket.
Repeat while R NULL.
bj (Obtain Jth digit of the key R
data)
D
Link.If T[D] = Null
Next = R
Then T[D] =B[d] = R
Else T[D] = Link = R
T[D] = R
Link = Null
R
R = Next
4 [ Combine Pockets]
P =0
Repeat while B[P] = NULL
P = P+1
First = B[P]
Repeat for I = P+1, P+2,..9
Prev = T[I-1]
If T[i] Null
Link = B[I]
Then Prev
Else T[i] =PREV
5.[Finished]
Return.
Push(s,x)
y=pop(s)
3 .
-1
n-1
-
tos
insert
delete
or
n-1 n
insert
tos
delete
Push(s,tos,n,x)
1. [check for overflow]
if(tos > n-1)
then printf(Overflow on push)
return
2. [Increment top of the stack]
tos = tos + 1
3. [Insert the element]
s[tos] = x
4. [Finished]
return
Pop(s,tos,)
1. [check for underflow]
if(tos <= -1)
then printf(underflow on pop)
return
2. [Decrement top of the stack]
tos = tos - 1
3. [Return the previous top of the stack]
return (s[tos+1])
Peep(s,tos,i)
1. [Check for underflow]
if(tos i+1 <= -1)
then printf (Underflow on peep)
return(-1)
2. [Return the ith element from tos]
return(s[tos-i+1])
Change(s,tos,i, x)
1. [Check for underflow]
if(tos i+1 <= -1)
then printf (Underflow on peep)
return(-1)
2. [update the ith element with x]
s[tos-i+1] = x
3. [Finished]
return
size
tos
sarray
struct stack
{
int size;
int tos;
int *sarray;
};
struct stack * createstack(int n)
{
struct stack * s;
s = (struct stack *)malloc (sizeof(struct stack));
if(s ==Null)
printf(out of space);
else
{
s->sarray =(int*)malloc (n *sizeof(int));
if( s->sarray = = NULL)
{
printf(out of space);
return(NULL);
}
else
{
s ->size = n-1;
s -> tos =-1;
}
}
return(s);
}
n-1
*, / % (2),
a,b,c..(3), #
(0).
i
ie[]
j
a
Pe[ ]
C -functions
int isoperator(char x)
{
if((x= =+)||(x= = -)||(x = = *)||(x = = /))
return(1);
else
return(0);
}
int precendence(Char x)
{
If((x= = *)||( x = = /))
return(2);
else
return(1);
}
top of the stack tos is global.
Stack Applications
To evaluate the given postfix expression
float Evalpost(Char pe[])
{ /* finds the value of the given postfix expression */
float x,y,z,s[15];
int i =0.
tos = -1;
while( pe[i] ! = #)
{
if(isoperator(pe[i])
{
y=pop(s);
x= pop(s);
switch(pe[i])
{
case + : z = x+y; break;
case - : z = x-y; break;
case * : z = x* y:break;
case / : z = x/y; break;
}
push(s,z);
}
else
{
printf(Enter the value of %c,pe[i]);
scanf(%f,&x);
push(s,x);
}
i++;
}
return(pop(s));
}
*function to check whether given character is symbol or not.
int issymbol(Char x)
{
if((x==()||(x= = ))||(x= = [)||(x= = ])||( x = = { )||( x= = }))
return(1);
else
return(0);
}
*function to check whether the two symbols are counter parts or not(x is a closing
symbol)
int iscounter(Char x,Char y)
{
switch(x)
{
Case ) : if(y= = ()
return(1);
else break;
Case ] : if (y = =[ )
return(1);
else break;
Case } : if( y = = { )
return(1);
else break;
}
return(0);
}
Implementing Two stacks in a single array
tos
-1
14
lb
10
15
14
19
rb
Initialization:
for(i=0 ;i<n ; i++)
{
tos[i] = m/n * i 1;
lb[i] = tos[i] +1;
rb[i] = (i+1) * m/n 1;
void push(int s[],int i,int x)
{
if(tos[i] >= rb[i] )
printf(Overflow on push);
else
{
tos[i]++;
s[tos[i] ] = x;
}
}
insert(q,x)
y=delete(q)
Queue(q)
y=delete(q)
y=dequeue(q)
exqueue(q,x)
Queue Applications:Queue is a checkout line at a Super market cash register.The first person inline is the first
to be Checked out.
Queue can be found in a time sharing computer system where many users share the
system simultaneously.
In multiprogram concept the os has to maintain different processes in ready queue ,
Waiting queue.etc.
In simulation:Simulation is the process of forming an abstract model from a real situation inorder to
understand the impact of modifications and the effect of introducing various strategies on
the situation.
Simulation allows the user to experiment with real and proposed situations otherwise
impossible or impractical.
The major advantage of simulation is that it permits experimentation without modifying
the real situation.
Military operations,pilot training programme etc.
* Queing theory.
Deletion
Insert
front
rear
Algorithms:qinsert(q,front,rear,n,x)
1. [check for overflow]
if (rear >= n-1)
printf (overflow)
return
2. [Increment rear pointer]
rear++
3. [Insert the element]
q[rear] = x
4. [Is front pointer properly set ?]
if(front = = -1)
front = 0
return
qdelete(q,front,rear)
1. [check for underflow]
if(front = = -1)
printf(underflow)
return(-1)
2. [Delete the element]
y= q[front]
3. [queue empty?]
if(front == rear)
front = rear = -1
else
front = front +1
4. [return the element]
return(y)
Disadvantage:The above implementation can be very wasteful of storage if the front pointer F never
manages to catch up to the rear pointer.An arbitrary large amount of memory would be
required to accommodate the elements.
0
1
2.n-1
ex:
x x
front rear
In the above example if we try to insert an element the insert will display an overflow
error even though there are n-2 free locations.
Circular queue
A more suitable method of representing a queue,which prevents an excessive use of
memory , is to arrange the elements q[0],q[1]..q[n] in a circular fashion with q[0]
follows.
Algorithms:
Cqinsert(cq,n,front ,rear, x)
1 [update rear pointer]
if(rear = = n+1)
rear = 0
else rear = rear + 1
2. [overflow ?]
if(front = = rear]
printf(overflow)
return
3. [Insert the element]
cq[rear] = x
4.[Is front pointer properly set ? ]
if(front = = -1)
front = 0;
return
Cqdelete(cq,n,front,rear)
1. [underflow?]
if(front = = -1)
printf(underflow)
return(-1);
2. [Delete the element]
y = cq[front]
3. [Is queue empty?]
if(front = = rear)
front = rear = -1
return(y);
4. [Update front pointer]
if(front = = n-1)
front = 0;
else
front++;
return(y)
Structure Implementation
Q
qsize
front
rear
qarray
struct queue{
int qsize;
int front;
int rear;
int *qarray;
};
struct queue * Create stack(int n)
{
struct queue * Q;
Q = (structqueue *) malloc (sizeof(struct queue));
if( Q = = NULL)
{
printf( out of space);
return(NULL);
}
else
{
Q -> qsize = n-1;
Q ->front = Q-> rear = -1;
}
return(Q);
}
HOME WORK: WRITE INSERT AND DELETE FUNCTIONS
n-1
insertion
x
insertion
empty deque: dq [ ]
Operations:
leftinsert,
rightinsert,
leftdelete,
rightdelete
x
deletion
leftinsert(dq,n,IL,IR,DL,DR,x)
1. [check for overflow]
if(IL-IR = = 1)
printf(overflow)
return
2. [Decrement IL]
IL =IL-1
3. [Insert the element
dq[IL] = x
4. [check DR for proper value]
if(DR = = n)
DR = DR 1
5. [Finished]
return
* rightdelete-rightmost element is to be deleted
rightdelete(dq,IL,IR,DL,DR)
1. [check for underflow]
if((DL = = -1) &&(DR = = n))
{
printf(underflow)
return(-1)
}
2. [Delete the rightmost element]
if(DR ! = n)
{
y= dq[DR]
if(DR = = IL)
DR = IL = n
else
DR = DR 1
}
else
{
y = dq[IR]
if(IR = = DL)
IR = DL = -1
else
IR = IR 1
}
3. [Finished]
return(y)