DS-Unit-I-Unit-V NOTES
DS-Unit-I-Unit-V NOTES
III/IIYR CSE
CSE CS8391-DATA
CS8391-DATA STRUCTURES
STRUCTURES
REGULATION:2017
SYLLABUS
CS8391 DATA STRUCTURES
OBJECTIVES:
1. To understand the concepts of ADTs
2. To Learn linear data structures – lists, stacks, and queues
3. To understand sorting, searching and hashing algorithms
4. To apply Tree and Graph structures
Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list implementation ––
singly linked lists- circularly linked lists- doubly-linked lists – applications of lists –Polynomial
Manipulation – All operations (Insertion, Deletion, Merge, Traversal).
Tree ADT – tree traversals - Binary Tree ADT – expression trees – applications of trees – binary
search tree ADT –Threaded Binary Trees- AVL Trees – B-Tree - B+ Tree - Heap – Applications of
heap
Searching- Linear Search - Binary Search. Sorting - Bubble sort - Selection sort - Insertion sort - Shell
sort – Radix sort. Hashing- Hash Functions – Separate Chaining – Open Addressing – Rehashing –
Extendible Hashing. TOTAL: 45
PERIODS
OUTCOMES:
At the end of the course, the student should be able to:
1. Implement abstract data types for linear data structures.
2. Apply the different linear and non-linear data structures to problem solutions.
3. Critically analyze the various sorting algorithms.
Page 1 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
TEXT BOOKS:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, 2nd Edition, PearsonEducation,1997.
2. Reema Thareja, “Data Structures Using C”, Second Edition , Oxford University Press,2011
REFERENCES:
1. Thomas H. Cormen, Charles E. Leiserson, Ronald L.Rivest, Clifford Stein, “Introduction
toAlgorithms", Second Edition, Mcgraw Hill, 2002.
2. Aho, Hopcroft and Ullman, “Data Structures and Algorithms”, Pearson Education,1983.
3. Stephen G. Kochan, “Programming in C”, 3rd edition, Pearson Education.
4. Ellis Horowitz, Sartaj Sahni, Susan Anderson-Freed, “Fundamentals of Data Structures in C”,
Second Edition, University Press, 2008
Page 2 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Data:
A collection of facts, concepts, figures, observations, occurrences or instructions in a
formalized manner.
Information:
The meaning that is currently assigned to data by means of the conventions applied to
those data(i.e. processed data)
Record:
Collection of related fields.
Data type:
Set of elements that share common set of properties used to solve a program.
Data Structures:
Data Structure is the way of organizing, storing, and retrieving data and their relationship
with each other.
Characteristics of data structures:
1. It depicts the logical representation of data in computer memory.
2. It represents the logical relationship between the various data elements.
1.Traversal
2.Search
3.Insertion
4.Deletion
Page 3 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
DATA STRUCTURES
Static Ds:
If a ds is created using static memory allocation, ie. ds formed when the number of data items
are known in advance ,it is known as static data static ds or fixed size ds.
Page 4 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Dynamic Ds:
If the ds is created using dynamic memory allocation i.e ds formed when the number of data
items are not known in advance is known as dynamic ds or variable size ds.
Compiler design
Operating system
Statistical analysis package
DBMS
Numerical analysis
Simulation
Artificial intelligence
Graphics
An abstract Data type (ADT) is defined as a mathematical model with a collection of operations
defined on that model. Set of integers, together with the operations of union, intersection and set
difference form a example of an ADT. An ADT consists of data together with functions that
operate on that data.
Advantages/Benefits of ADT:
1.Modularity
2.Reuse
3.code is easier to understand
4.Implementation of ADTs can be changed without requiring changes to the program that uses
the ADTs.
If the element at position i is Ai, then its successor is Ai+1 and its predecessor is Ai-1
Page 5 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Insertion and Deletion operation are expensive as it requires more data movements
Page 6 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Declaration of Array:
#define maxsize 10
int list[maxsize], n ;
Create Operation:
Create operation is used to create the list with „ n „ number of elements .If „ n „ exceeds the
array‟s maxsize, then elements cannot be inserted into the list. Otherwise the array elements are
stored in the consecutive array locations (i.e.) list [0], list [1] and so on.
void Create ( )
{
int i;
printf("\nEnter the number of elements to be added in the list:\t");
scanf("%d",&n);
printf("\nEnter the array elements:\t");
for(i=0;i<n;i++)
scanf("%d",&list[i]);
}
Insert Operation:
Insert operation is used to insert an element at particular position in the existing list. Inserting the
element in the last position of an array is easy. But inserting the element at a particular position
in an array is quite difficult since it involves all the subsequent elements to be shifted one
position to the right.
Page 7 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
10 20 30 40 50
If data 15 is to be inserted in the 2nd position then 50 has to be moved to next index position, 40
has to be moved to 50 position, 30 has to be moved to 40 position and 20 has to be moved to
30 position.
10 20 30 40 50
10 20 30 40 50
After this four data movement, 15 is inserted in the 2nd position of the array.
Page 8 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
10 15 20 30 40 50
Deletion Operation:
Deletion is the process of removing an element from the array at any position.
Deleting an element from the end is easy. If an element is to be deleted from any particular
position ,it requires all subsequent element from that position is shifted one position towards
left.
Routine to delete an element in the array:
void Delete( )
{
int i, pos ;
printf("\nEnter the position of the data to be deleted:\t");
scanf("%d",&pos);
printf("\nThe data deleted is:\t %d", list[pos-1]);
for(i=pos-1;i<n-1;i++)
list[i]=list[i+1];
n=n-1;
Display();
}
Consider an array with 5 elements [ max elements = 10 ]
10 20 30 40 50
If data 20 is to be deleted from the array, then 30 has to be moved to data 20 position, 40 has to
be moved to data 30 position and 50 has to be moved to data 40 position.
10 20 30 40 50
Page 9 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
After this 3 data movements, data 20 is deleted from the 2nd position of the array.
10 30 40 50
Search Operation:
Search( ) operation is used to determine whether a particular element is present in the list or not.
Input the search element to be checked in the list.
Routine to search an element in the array:
void Search( )
{
int search,i,count = 0;
printf("\nEnter the element to be searched:\t");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(search == list[i])
count++;
}
Page 10 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if(count==0)
printf("\nElement not present in the list");
else
printf("\nElement present in the list");
}
Page 11 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 12 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void Search()
{
int search,i,count = 0;
printf("\nEnter the element to be searched:\t");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(search == list[i])
{
count++;
}
}
if(count==0)
printf("\nElement not present in the list");
else
printf("\nElement present in the list");
}
Output
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Enter your choice: 1
1 2 3 4 5
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Page 13 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
3 1 2 3 4 5
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
3 1 2 4 5
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Page 14 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Enter your choice:6
Page 15 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Linked Lists:
A Linked list is an ordered collection of elements. Each element in the list is referred as a node.
Each node contains two fields namely,
Data field-The data field contains the actual data of the elements to be stored in the list
Next field- The next field contains the address of the next node in the list
DATA NEXT
10 40 20 30 Null
L
Advantages of Linked list:
1.Insertion and deletion of elements can be done efficiently
2.It uses dynamic memory allocation
3.Memory utilization is efficient compared to arrays
Disadvantages of linked list:
1.Linked list does not support random access
2.Memory is required to store next field
3.Searching takes time compared to arrays
Types of Linked List
1. Singly Linked List or One Way List
2. Doubly Linked List or Two-Way Linked List
3. Circular Linked List
Dynamic allocation
The process of allocating memory to the variables during execution of the program or at run time
is known as dynamic memory allocation. C language has four library routines which allow this
function.
Dynamic memory allocation gives best performance in situations in which we do not know
memory requirements in advance. C provides four library routines to automatically allocate
memory at the run time.
Page 16 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
To use dynamic memory allocation functions, you must include the header file stdlib.h.
malloc()
The malloc function reserves a block of memory of specified size and returns a pointer of type
void. This means that we can assign it to any type of pointer.
The general syntax of malloc() is
ptr =(cast-type*)malloc(byte-size);
where ptr is a pointer of type cast-type. malloc() returns a pointer (of cast type) to an area of
memory with size byte-size.
calloc():
calloc() function is another function that reserves memory at the run time. It is normally used to
request multiple blocks of storage each of the same size and then sets all bytes to zero. calloc()
stands for contiguous memory allocation and is primarily used to allocate memory for arrays.
The syntax of calloc() can be given as:
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each of size elem-size bytes. The
only difference between malloc() and calloc() is that when we use calloc(), all bytes are
initialized to zero. calloc() returns a pointer to the first byte of the allocated region.
free():
The free() is used to release the block of memory.
Syntax:
The general syntax of the free()function is,
free(ptr);
where ptr is a pointer that has been created by using malloc() or calloc(). When memory is
deallocated using free(), it is returned back to the free list within the heap.
realloc():
At times the memory allocated by using calloc() or malloc() might be insufficient or in excess.
In both the situations we can always use realloc() to change the memory size already allocated
by calloc() and malloc(). This process is called reallocation of memory. The general syntax for
realloc() can be given as,
ptr = realloc(ptr,newsize);
The function realloc() allocates new memory space of size specified by newsize to the pointer
Page 17 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
variable ptr. It returns a pointer to the first byte of the memory block. The allocated new block
may be or may not be at the same region. Thus, we see that realloc() takes two arguments. The
first is the pointer referencing the memory and the second is the total number of bytes you want
to reallocate.
A singly linked list is a linked list in which each node contains only one link field pointing to the
next node in the list
SLL
Page 18 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
};
Creation of the list:
This routine creates a list by getting the number of nodes from the user. Assume n=4 for this
example.
void create()
{
int i,n;
L=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the number of nodes to be inserted\n");
scanf("%d",&n);
printf("\n Enter the data\n");
scanf("%d",&newnode->data);
newnode->next=NULL;
L=newnode;
p=L;
for(i=2;i<=n;i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
scanf("%d",&newnode->data);
newnode->next=NULL;
Page 19 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
p->next=newnode;
p=newnode;
}
}
Initially the list is empty
List L
Null
L
Insert(10,List L)- A new node with data 10 is inserted and the next field is updated to
NULL. The next field of previous node is updated to store the address of new node.
10 Null
L
P
Insert(20,L) - A new node with data 20 is inserted and the next field is updated to NULL.
The next field of previous node is updated to store the address of new node.
10 20 Null
L P
Insert(30,L) - A new node with data 30 is inserted and the next field is updated to NULL. The
next field of previous node is updated to store the address of new node.
10 20 30 Null
L P
Page 20 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
p=L;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the data to be inserted\n");
scanf("%d",&newnode->data);
newnode->next=L;
L=newnode;
}
Case 2:Routine to insert an element in list at Position
This routine inserts an element X after the position P.
Void Insert(int X, List L, position p)
{
position newnode;
newnode =(struct node*) malloc( sizeof( struct node ));
if( newnode = = NULL )
Fatal error( “ Out of Space ” );
else
{
Newnode -> data = x ;
Newnode -> next = p ->next ;
P -> next = newnode ;
}
}
Insert(25,L, P) - A new node with data 25 is inserted after the position P and the next field is
updated to NULL. The next field of previous node is updated to store the address of new node.
Page 21 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
{
p=L;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the data to be inserted\n");
scanf("%d",&newnode->data);
while(p->next!=NULL)
p=p->next;
newnode->next=NULL;
p->next=newnode;
p=newnode;
}
Routine to check whether a list is Empty
This routine checks whether the list is empty .If the lis t is empty it returns 1
Page 22 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
10 40 20 30 Null
Find(List L, 20) - To find an element X traverse from the first node of the list and move to
the next with the help of the address stored in the next field until data is equal to X or till the
end of the list
10 40 20 30 Null
X P
Page 23 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Find Previous
It returns the position of its predecessor.
position FindPrevious (int X, List L)
{
position p;
p = L;
while( p -> next ! = NULL && p -> next -> data! = X )
p = p -> next;
return P;
}
Page 24 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 25 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void Delete_list(List L)
{
position P,temp;
P=L->next;
L->next=NULL;
while(P!=NULL)
{
temp=P->next;
free(P);
P=temp;
}
}
Page 26 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
int data;
position next; 1
};
void main()
{ Enter the number of
int choice;
clrscr(); nodes to be inserted
do
5
{
printf("1.create\n2.display\n3.insert\n4.find\n5.delete\n\n\n"); Enter the data
printf("Enter your choice\n\n");
1
scanf("%d",&choice);
switch(choice) 2
{
3
case 1:
create(); 4
break; 5
case 2:
display(); 1.create
break; 2.display
case 3:
insert(); 3.insert
break; 4.find
case 4:
find(); 5.delete
break; Enter your choice
case 5:
delete(); 2
break; 1 -> 2 -> 3 -> 4 -> 5 ->
case 6:
exit(0); Null
} 1.create
}
while(choice<7); 2.display
getch(); 3.insert
}
void create() 4.find
{ 5.delete
int i,n;
L=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the number of nodes to be inserted\n");
scanf("%d",&n); Enter your choice
printf("\n Enter the data\n");
scanf("%d",&newnode->data);
newnode->next=NULL; 3
Page 27 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
L=newnode; p=L;
for(i=2;i<=n;i++) Enter ur choice
{
newnode=(struct node *)malloc(sizeof(struct node));
scanf("%d",&newnode->data); 1.first
newnode->next=NULL;
2.middle
p->next=newnode;
p=newnode; 3.end
}
} 1
void display()
{ p=L;
while(p!=NULL) Enter the data to be
{ inserted
printf("%d -> ",p->data);
p=p->next; 7
} 7 -> 1 -> 2 -> 3 -> 4 -> 5 -
printf("Null\n");
} > Null
void insert()
1.create
{
int ch; 2.display
printf("\nEnter ur choice\n"); 3.insert
printf("\n1.first\n2.middle\n3.end\n"); 4.find
scanf("%d",&ch);
switch(ch) 5.delete
{
case 2:
{ Enter your choice
int pos,i=1;
p=L;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the data to be inserted\n");
scanf("%d",&newnode->data);
printf("\nEnter the position to be inserted\n");
scanf("%d",&pos);
newnode->next=NULL;
while(i<pos-1)
{
p=p->next;
i++;
}
newnode->next=p->next;
p->next=newnode;
Page 28 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
p=newnode;
display();
break;
}
case 1:
{
p=L;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the data to be inserted\n");
scanf("%d",&newnode->data);
newnode->next=L;
L=newnode;
display();
break;
}
case 3:
{
p=L;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the data to be inserted\n");
scanf("%d",&newnode->data);
while(p->next!=NULL)
p=p->next;
newnode->next=NULL;
p->next=newnode;
p=newnode;
display();
break;
}
}
}
void find()
{
int search,count=0;
printf("\n Enter the element to be found:\n");
scanf("%d",&search);
p=L;
while(p!=NULL)
{
if(p->data==search)
{
count++;
break;
}
p=p->next;
}
Page 29 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if(count==0)
printf("\n Element Not present\n");
else
printf("\n Element present in the list \n\n");
}
void delete()
{
position p,temp;
int x; p=L;
if(p==NULL)
{
printf("empty list\n");
}
else
{
printf("\nEnter the data to be deleted\n");
scanf("%d",&x);
if(x==p->data)
{ temp=p;
L=p->next;
free(temp);
display();
}
else
{
while(p->next!=NULL && p->next->data!=x)
{
p=p->next;
}
temp=p->next;
p->next=p->next->next;
free(temp);
display();
}
}
}
Advantages of SLL
1.The elements can be accessed using the next link
2.Occupies less memory than DLL as it has only one next field.
Disadvantages of SLL
1.Traversal in the backwards is not possible
2.Less efficient to for insertion and deletion.
Page 30 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Doubly-Linked List
A doubly linked list is a linked list in which each node has three fields namely Data, Next, Prev.
DLL NODE
Page 31 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Initially the list is empty. Then assign the first node as head.
newnode->data=X;
newnode->next=NULL;
newnode->prev=NULL;
L=newnode;
list. If we add one more node in the list,then create a newnode and attach that node to the end of the
L->next=newnode;
newnode->prev=L;
if(pos==1)
P=L;
if (Newnode! = NULL)
Newnode->data= X;
L->next ->prev=Newnode
L->next = Newnode;
Newnode ->prev = L;
Page 32 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if (Newnode! = NULL)
Newnode->data= X;
P->next ->prev=Newnode
P ->next = Newnode;
Newnode ->prev = P:
Page 33 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 34 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void find()
{
int a,flag=0,count=0;
if(L==NULL)
printf(“\nThe list is empty”);
else
{
printf(“\nEnter the elements to be searched”);
scanf(“%d”,&a);
for(P=L;P!=NULL;P=P->next)
{
count++;
if(P->data==a)
{
flag=1;
printf(“\nThe element is found”);
printf(“\nThe position is %d”,count);
Page 35 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
break;
}
}
if(flag==0)
printf(“\nThe element is not found”);
}
}
Pr#oignrcalm
ud2e<:sIm
tdpiole.hm>entation of Doubly linked list Output
#include<conio.h>
void insert();
void deletion();
void display(); 1.INSERT
void find();
typedef struct node *position; 2.DELETE
position newnode,temp,L=NULL,P; 3.DISPLAY
struct node
{ 4.FIND
int data; 5.EXIT
position next;
position prev; Enter ur option1
};
void main()
{ Enter the data to be
int choice; inserted10
clrscr();
do
{ printf(“\n1.INSERT”); 1.INSERT
printf(“\n2.DELETE”);
printf(“\n3.DISPLAY”); 2.DELETE
printf(“\n4.FIND”); 3.DISPLAY
printf(“\n5.EXIT”);
printf(“\nEnter ur option”); 4.FIND
scanf(“%d”,&choice); 5.EXIT
switch(choice)
{ Enter ur option1
case 1:
insert();
break; Enter the data to be
case 2:
inserted 20
deletion();
break;
case 3:
Enter the position where
display();
the data is to be inserted 2
Page 36 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
break; 1.INSERT
case 4: 2.DELETE
find();
break; 3.DISPLAY
case 5: 4.FIND
exit(1);
} 5.EXIT
}while(choice!=5); Enter ur option1
getch();
}
void insert() Enter the data to be
{
int pos,I; inserted 30
newnode=(struct node*)malloc(sizeof(struct node));
printf(“\nEnter the data to be inserted”);
scanf(“%d”,&newnode->data); Enter the position where
if(L==NULL) the data is to be inserted3
{
L=newnode;
L->next=NULL; 1.INSERT
L->prev=NULL;
} 2.DELETE
else 3.DISPLAY
{
printf(“\nEnter the position where the data is to be inserted”); 4.FIND
scanf(“%d”,&pos); 5.EXIT
if(pos==1)
{ Enter ur option 3
newnode->next=L;
newnode->prev=NULL;
L->prev=newnode; The elements in the list
L=newnode; are
}
else 10 20 30
{ 1.INSERT
P=L;
for(i=1;i<pos-1&&P->next!=NULL;i++) 2.DELETE
{ 3.DISPLAY
P=P->next;
} 4.FIND
newnode->next=P->next; 5.EXIT
P->next=newnode;
newnode->prev=P; Enter ur option 2
P->next->prev=newnode;
}
}
Page 37 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 38 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if(L==NULL)
printf(“\nThe list is empty”);
Enter the elements to be
else
{ searched 30
printf(“\nEnter the elements to be searched”);
scanf(“%d”,&a);
for(P=L;P!=NULL;P=P->next) The element is found
{
The position is 2
count++;
if(P->data==a) 1.INSERT
{
2.DELETE
flag=1;
printf(“\nThe element is found”); 3.DISPLAY
printf(“\nThe position is %d”,count);
4.FIND
break;
} 5.EXIT
}
Enter ur option5
if(flag==0)
printf(“\nThe element is not found”); Press any key to continue .
}
..
}
Advantages of DLL:
The DLL has two pointer fields. One field is prev link field and another is next link field.
Because of these two pointer fields we can access any node efficiently whereas in SLL only one
link field is there which stores next node which makes accessing of any node difficult.
Disadvantages of DLL:
The DLL has two pointer fields. One field is prev link field and another is next link field.
Because of these two pointer fields, more memory space is used by DLL compared to SLL
Circular Linked list is a linked list in which the pointer of the last node points to the first node.
Page 39 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Types of CLL:
CLL can be implemented as circular singly linked list and circular doubly linked list.
A Singly linked circular list is a linked list in which the last node of the list points to the first
node.
Declaration of node:
typedef struct node *position;
struct node
int data;
position next;
};
Page 40 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 41 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 42 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void del_first(List L)
{
position temp;
temp=L->next;
L->next=temp->next;
free(temp);
}
Page 43 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
CS6202 42 PDS-1NOTES
Page 44 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void del_last(List L)
{
position p, temp;
p=L;
while(p->next->next!=L)
p=p->next;
temp=p->next;
p->next=L
free(temp);}
Page 45 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
A doubly linked circular list is a doubly linked list in which the next link of the last node points
to the first node and prev link of the first node points to the last node of the list.
Page 46 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Declaration of node:
Page 47 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 48 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 49 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void del_first(List L)
{
position temp;
if(L->next!=NULL)
{
temp=L->next;
L->next=temp->next;
temp->next->prev=L;
free(temp);
}
Page 50 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 51 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void del_last(List L)
{
position p, temp;
p=L;
while(p->next!=L)
p=p->next;
temp=p;
p->next->prev=L;
L->prev=p->prev;
free(temp);
}
Page 52 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Applications of List:
1.Polynomial ADT
2.Radix sort
3.Multilist
Polynomial Manipulation
Polynomial manipulations such as addition, subtraction & differentiation etc.. can be
performed using linked list
Page 53 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 54 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 55 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
newnode->coeff=(ptr1-coeff)-(ptr2->coeff);
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
ptr2=ptr2->next;
}
else
{
if(ptr1-power>ptr2-power)
{
newnode->coeff=ptr1->coeff;
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
else
{
newnode->coeff=-(ptr2->coeff);
newnode->power=ptr2->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr2=ptr2->next;
}
}
}
Polynomial Differentiation:
void diff()
newnode->coeff=(ptr1-coeff)*(ptr1->power);
newnode->power=ptr1->power-1;
Page 56 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
}
Polynomial Multiplication
void mul()
{
poly *ptr1, *ptr2, *newnode ;
ptr1= list1;
ptr2 = list2;
while( ptr1 != NULL && ptr2 != NULL )
{
newnode = (struct poly*)malloc( sizeof ( struct poly ));
if( ptr1 -> power = = ptr2 -> power )
{
newnode -> coeff = ptr1 -> coeff * ptr2 -> coeff;
newnode -> power = ptr1 -> power+ptr2->power; ;
newnode -> next = NULL;
list3 = create( list3, newnode );
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}}
}
Page 57 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
STACK
Stack is a Linear Data Structure that follows Last In First Out(LIFO) principle.
Insertion and deletion can be done at only one end of the stack called TOP of the stack.
Example: - Pile of coins, stack of trays
STACK ADT:
STACK MODEL
TOP pointer
Two fundamental operations performed on the stack are PUSH and POP.
(a) PUSH:
Page 58 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
1. Stack Overflow
An Attempt to insert an element X when the stack is Full, is said to be stack
overflow.
For every Push operation, we need to check this condition.
2. Stack Underflow:
Page 59 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
return(1);
Page 60 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 61 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
int TopElement(Stack S)
{
if(Top==-1)
{
Error(“Empty stack!!No elements”);
return 0;
}
else
return S[Top];
}
#include<stdio.h>
#include<conio.h>
#define size 5
int stack [ size ];
int top;
void push( )
{
int n ;
printf( "\n Enter item in stack" ) ;
scanf( " %d " , &n ) ;
if( top = = size - 1)
{
printf( "\nStack is Full" ) ;
}
else
{
top = top + 1 ;
Page 62 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
stack [ top ] = n ;
}
}
void pop( )
{
int item;
if( top = = - 1)
{
printf( "\n Stack is empty" );
}
else
{
item = stack[ top ] ;
printf( "\n item popped is = %d" , item );
top - -;
}
}
void display( )
{
int i;
printf("\n item in stack are");
for(i = top; i > = 0; i --)
printf("\n %d", stack[ i ] );
}
void main( )
{
char ch,ch1;
ch = 'y';
ch1 = 'y';
top = -1;
clrscr( );
while(ch !='n')
{
push( );
printf("\n Do you want to push any item in stack y/n");
ch=getch( );
}
display( );
while( ch1!='n' )
{
printf("\n Do you want to delete any item in stack y/n");
ch1=getch( );
pop( );
}
display( );
getch( );}
Page 63 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
OUTPUT:
Enter item in stack20
Do you want to push any item in stack y/n
Enter item in stack25
Do you want to push any item in stack y/n
Enter item in stack30
Stack is Full
Do you want to push any item in stack y/n
item in stack are
25
20
15
10
5
Do you want to delete any item in stack y/n
item popped is = 25
Do you want to delete any item in stack y/n
item popped is = 20
Do you want to delete any item in stack y/n
item popped is = 15
item in stack are
10
5
Linked list implementation of Stack
Stack elements are implemented using SLL (Singly Linked List) concept.
Dynamically, memory is allocated to each element of the stack as a node.
Type Declarations for Stack using SLL
struct node;
typedef struct node *stack;
typedef struct node *position;
stack S;
struct node{ int
data; position
next;};
int IsEmpty(Stack S);
void Push(int x, Stack S);
void Pop(Stack S);
int TopElement(Stack S);
Page 64 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Header
30 20 10 NULL
40
newnode
Before Insertion
Page 65 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Header
40 30 20 10 NULL
After Insertion
TOP
(iii) Pop Operation
It is the process of deleting the Top element of the stack.
With Linked List implementations, the element at the Front of the List
(i.e.) S -> next is always deleted.
It takes only one parameter. Pop(X).The element X to be deleted from the Front of the
List.
Before deleting the front element in the list, check for Empty Stack.
If the Stack is Empty, deletion is not possible.
Otherwise, make the front element in the list as “temp”.
Update the next field of header.
Using free ( ) function, Deallocate the memory allocated for temp node.
Page 66 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
PANIMALAR
S
Header
40 30 20 10 NULL
TOP
Before Deletion
Pop routine /*Deletes the element at front of list
void Pop( Stack S )
{
Position temp, Top;
Top = S -> next;
if( S -> next = = NULL)
Error(“empty stack! Pop not possible”);
else
{
Temp = S -> next;
S -> next = temp -> next;
free(temp);
Top = S -> next;
}}
Header
40 30 20 10 NULL
HEADER
30 20 10 NULL
A fter Deletion
TOP
Page 67 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if(S->next==NULL)
error(“Stack is empty”);
return 0;
else
return S->next->data;
}
S
Header
40 30 20 10 NULL
TOP
Page 68 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
case 4:
display();
break;
case 5:
exit(0);
}
}while(op<5);
Page 69 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
getch();
}
void create()
{
int n,i;
s=NULL;
printf("Enter the no of nodes to be created\n");
scanf("%d",&n);
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=NULL;
top=newnode;
s=newnode;
for(i=2;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=top;
s=newnode;
top=newnode;
}}
void display()
{ top=s;
while(top!=NULL)
{
printf("%d->",top->data);
top=top->next;
}
printf("NULL\n");
}
void push()
{ top=s;
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
newnode->next=top;
top=newnode;
s=newnode;
display();
}
void pop()
{
top=s;
Page 70 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
if(top==NULL)
printf("Empty stack\n\n");
else
{
temp=top;
printf("Deleted element is \t %d\n\n",top->data);
s=top->next;
free(temp);
display();
}}
Output
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ? 1
Enter the no of nodes to be created5
Enter the data 10
Enter the data20
Enter the data30
Enter the data40
Enter the data50
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ? 4
50->40->30->20->10->NULL
### Linked List Implementation of STACK Operations ###
Press 1-create
2-Push
3-Pop
4-Display
5-Exit
Your option ?2
Enter the data60
Your option ? 4
60->50->40->30->20->10->NULL
Your option ?2
Enter the data70
Your option ? 4
Page 71 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
70->60->50->40->30->20->10->NULL
Your option ?3
Deleted element is70
Your option ? 4
50->40->30->20->10->NULL
Applications of Stack
INFIX:
The arithmetic operator appears between the two operands to which it is being
applied.
POSTFIX:
The arithmetic operator appears directly after the two operands to which it applies.
Also called reverse polish notation.
Page 72 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
PREFIX:
The arithmetic operator is placed before the two operands to which it applies. Also
called polish notation.
Read the infix expression one character at a time until it encounters the delimiter “#”
Step 2: If the character is an operator, push it onto the stack. If the stack operator has a higher or
equal priority than input operator then pop that operator from the stack and place it onto the
output.
Step 3:If the character is left parenthesis, push it onto the stack
Step 4:If the character is a right parenthesis, pop all the operators from the stack till it encounters
left parenthesis, discard both the parenthesis in the output.
Page 73 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
A A
*
A
B
+ AB
*
+ AB*
( AB*
(
+
272
Page 74 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
C AB*C
(
+
-
- AB*C
(
+
D -
AB*CD
(
+
/
/ AB*CD
-
(
+
E / AB*CDE
-
(
+
AB*CDE/-
) /
-
(
+
Page 75 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
AB*CDE/-+
Read the postfix expression one character at a time until it encounters the delimiter „#‟
Step 1: If the character is an operand, push its associated value onto the stack.
Step 2: If the character is an operator, POP two values from the stack, apply the operator to
them and push the result onto the stack.
Operand Value
A 2
B 3
C 4
D 4
E 2
A 2
3
B
2
Page 76 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
* 6
4
C
6
4
D 4
6
2
/ 4
6
2
- 6
+ 8
OUTPUT = 8
(
(
a a
(
Page 77 of 272
271 P
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
+ a
+
(
b ab
+
(
) ab+
* ab+
c ab+c
/ ab+c*
d ab+c*d
ab+c*d/
+
21
Page 78 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
e ab+c*d/e
/ ab+c*d/e
/
+
f ab+c*d/ef
/
+
# ab+c*d/ef/+
Operand Value
a 1
b 2
c 4
d 2
e 6
f 3
Page 79 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
a 1
2
b
1
+ 3
4
c 3
* 12
2
d
12
/ 6
6
e
6
3
F 6
6
2
/
6
+ 8
Output = 8
Page 80 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
char pop()
{
return(s[top--]);
} (a+b)-(c-d)
Void main()
{ /* Main Program */
char infx[50],pofx[50],ch,elem;
int i=0,k=0;
printf("\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
Page 81 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
pofx[k++]=pop();
elem=pop(); /* Remove */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from stack
till empty
pofx[k++]=pop();
pofx[k]='\0'; /* Make pofx as valid
string */
printf("\n\nGiven Infix Expn: %s Postfix
Expn: %s\n",infx,pofx);
}
Towers of Hanoi
Towers of Hanoi can be easily implemented using recursion. Objective of the problem is
moving a collection of N disks of decreasing size from one pillar to another pillar. The
movement of the disk is restricted by the following rules.
Rule 2 : No larger disk could ever reside on a pillar on top of a smaller disk.
Rule 3 : A 3rd pillar could be used as an intermediate to store one or more disks, while they
A B C
Page 82 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Recursive Solution
Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C, The move
the 1st disk from B to C.
Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as
intermediate. Then the 3rd disk is moved from A to C. Then repeat the step (2) to move 2 disks
from B to C using A as intermediate.
In general, to move N disks. Apply the recursive technique to move N - 1 disks from A to B
using C as an intermediate. Then move the Nth disk from A to C. Then again apply the recursive
technique to move N - 1 disks from B to C using A as an intermediate
272
Page 83 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 84 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Since disks are moved from each tower in a LIFO manner, each tower may be considered
as a Stack. Least Number of moves required solving the problem according to our algorithm is
given by,
O(N)=O(N-1)+1+O(N-1) =2N-1
Function Calls
When a call is made to a new function all the variables local to the calling routine need to
be saved, otherwise the new function will overwrite the calling routine variables. Similarly the
current location address in the routine must be saved so that the new function knows where to go
after it is completed.
Call
balance()
Call push()
Page 85 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
int fact(int n)
{
int S;
if(n==1)
return(1);
else
S = n * fact( n – 1 );
return(S)
}
Compilers check the programs for errors, a lack of one symbol will cause an error.
A Program that checks whether everything is balanced.
Every right parenthesis should have its left parenthesis.
Check for balancing the parenthesis brackets braces and ignore any other character.
272
Page 86 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
((B*B)-{4*A*C}/[2*A]) #
( (
(
)
(
{ {
(
}
(
Page 87 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
[ [
(
]
(
Empty stack, hence the symbols the balanced in the given expression.
Page 88 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Page 89 of 272
271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
QUEUES:
Queue is a Linear Data Structure that follows First in First out (FIFO) principle.
Insertion of element is done at one end of the Queue called “Rear “end of the Queue.
Deletion of element is done at other end of the Queue called “Front “end of the Queue.
Example: - Waiting line in the ticket counter.
Front End
RearEnd
QUEUE Q
Deletion
Insertion
Queue Model
Front Pointer:-
Rear Pointer:-
Front (F) = - 1
Rear (R) = - 1
Operations on Queue
1. EnQueue
2. DeQueue
Page 90 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
It is the process of inserting a new element at the rear end of the Queue.
For every EnQueue operation
o Check for Full Queue
o If the Queue is full, Insertion is not possible.
o Otherwise, increment the rear end by 1 and then insert the element in the rear end
of the Queue.
It is the process of deleting the element from the front end of the queue.
For every DeQueue operation
o Check for Empty queue
o If the Queue is Empty, Deletion is not possible.
o Otherwise, delete the first element inserted into the queue and then increment the
front by 1.
Queue Overflow
Queue Underflow
An Attempt to insert an element X at the Rear end of the Queue when the
Queue is full is said to be Queue overflow.
For every Enqueue operation, we need to check this condition.
(ii) Queue Underflow:
An Attempt to delete an element from the Front end of the Queue when the
Queue is empty is said to be Queue underflow.
For every DeQueue operation, we need to check this condition.
Page99
Page 91 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Implementation of Queue
Page 92 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
return ( 1 );
As we keep inserting the new elements at the Rear end of the Queue, the Queue becomes
full.
When the Queue is Full, Rear reaches its maximum Arraysize.
For every Enqueue Operation, we need to check for full Queue condition.
Routine to check for Full Queue
int IsFull( Queue Q )
if ( Rear = = ArraySize - 1 )
return ( 1 );
Page93
Page 93 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
It is the process of inserting a new element at the Rear end of the Queue.
It takes two parameters, Enqueue(X, Q). The elements X to be inserted at the Rear end of
the Queue Q.
Before inserting a new Element into the Queue, check for Full Queue.
Page
Page94
94 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
It takes one parameter, DeQueue (Q). Always front element in the Queue will be deleted.
Before deleting an Element from the Queue, check for Empty Queue.
Page
Page95
95 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = - 1;
int rear = - 1;
int q[SIZE];
void insert( );
void del( );
void display( );
void main( )
{
int choice;
clrscr( );
do
{
printf("\t Menu");
printf("\n 1. Insert");
printf("\n 2. Delete");
printf("\n 3. Display ");
printf("\n 4. Exit");
Page 96 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
void del( )
{
if(front = = - 1)
{
printf("\n Queue Underflow");
return;
}
else
{
printf("\n Deleted Item:-->%d\n", q[front]);
}
if(front = = rear)
{ output
Front = - 1;
Rear = - 1;
}
else
{
Front = front + 1;
}}
void display( )
{
int i;
if( front = = - 1)
{
printf("\nQueue is empty....");
return;
}
for(i = front; i<=rear; i++)
printf("\t%d",q[i]);}
Page 97 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Header
10 20 30 40 NULL
Front Rear
struct node;
typedef struct node * Queue;
typedef struct node * position;
int IsEmpty (Queue Q);
Queue CreateQueue (void);
void MakeEmpty (Queue Q);
void Enqueue (int X, Queue Q);
void Dequeue (Queue Q);
struct node
{
int data ;
position next;
}* Front = NULL, *Rear = NULL;
Page 98 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
It is the process of inserting a new element at the Rear end of the Queue.
It takes two parameters, EnQueue ( int X , Queue Q ). The elements X to be inserted into
the Queue Q.
Using malloc ( ) function allocate memory for the newnode to be inserted into the Queue.
If the Queue is Empty, the newnode to be inserted will become first and last node in the
list. Hence Front and Rear points to the newnode.
Otherwise insert the newnode in the Rear -> next and update the Rear pointer.
Page 99 of 271
III/IIYR CSE
III/IIYR CSE CS8351-DATA STRUCTURES
CS8391-DATA STRUCTURES
Rear = newnode;
}
}
Q
Header NULL
Q
Before Insertion
Front Rear
(iii) DeQueue Operation After Insertion
Header
20 30 40 NULL
Front Rear
struct node
{
int data;
position next;
};
void main()
{
int choice;
clrscr();
do
{
printf("1.Enqueue\n2.Dequeue\n3.display\n4.exit\n");
printf("Enter your choice\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
while(choice<5);
}
void enqueue()
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the data to be enqueued\n");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(rear==NULL)
front=rear=newnode;
else {
rear->next=newnode;
rear=newnode;
}
display();
}
void dequeue()
{
if(front==NULL)
printf("\nEmpty queue!!!!! Deletion not possible\n");
else if(front==rear)
{
printf("\nFront element %d is deleted from queue!!!! now queue is
empty!!!! no more deletion possible!!!!\n",front->data);
front=rear=NULL;
}
else
{
temp=front;
front=front->next;
printf("\nFront element %d is deleted from queue!!!!\n",temp->data);
free(temp);
}
display();
}
void display()
{
p=front;
while(p!=NULL)
{
printf("%d -> ",p->data);
p=p->next;
}
printf("Null\n");
}
Output
Applications of Queue
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrive, First come first served.
4. Batch processing in operating system.
5. Job scheduling Algorithms like Round Robin Algorithm uses Queue.
With the array implementation of Queue, the element can be deleted logically only by
moving Front = Front + 1.
Here the Queue space is not utilized fully.
CIRCULAR QUEUE
In Circular Queue, the insertion of a new element is performed at the very first location of the
queue if the last location of the queue is full, in which the first element comes just after the last
element.
A circular queue is an abstract data type that contains a collection of data which allows
addition of data at the end of the queue and removal of data at the beginning of the
queue.
Circular queues have a fixed size.
Circular queue follows FIFO principle.
Queue items are added at the rear end and the items are deleted at front end of the circular
queue
Here the Queue space is utilized fully by inserting the element at the Front end if the rear
end is full.
It is same as Linear Queue EnQueue Operation (i.e) Inserting the element at the Rear end.
If the Rear end is full, the elements start getting inserted from the Front end.
Routine to Enqueue an element in circular queue
It is same as Linear Queue DeQueue operation (i.e) deleting the front element.
void insert()
{
int x;
if((front==0&&rear==max-1)||(front>0&&rear==front-1))
printf("Queue is overflow\n");
else
{
printf("Enter element to be insert:");
scanf("%d",&x);
if(rear==max-1&&front>0)
{ rear=0;
q[rear]=x;
}
else
{
if((front==0&&rear==-1)||(rear!=front-1))
q[++rear]=x;
} }}
void delet()
{
int a;
if((front==0)&&(rear==-1))
printf("Queue is underflow\n");
if(front==rear)
{
a=q[front];
rear=-1;
front=0;
}
else if(front==max-1)
{
a=q[front];
front=0;
}
else
a=q[front++];
printf("Deleted element is:%d\n",a);
}
void display()
{
int i,j; if(front==0&&rear==-1)
printf("Queue is underflow\n");
if(front>rear) {
for(i=0;i<=rear;i++)
printf("\t%d",q[i]);
for(j=front;j<=max-1;j++)
printf("\t%d",q[j]);
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]); }
else
{
for(i=front;i<=rear;i++)
printf("\t%d",q[i]); printf("\nrear
is at %d\n",q[rear]); printf("\nfront
is at %d\n",q[front]);
}
printf("\n");
}
OUTPUT
In DEQUE, insertion and deletion operations are performed at both ends of the Queue.
Insertion
Deletion
Deletion
Front Rear
Here insertion is allowed at both ends and deletion is allowed at one end.
Insertion
Insertion
Deletion
Front Rear
Operations on DEQUE
Four cases for inserting and deleting the elements in DEQUE are
else
{
Rear = Rear + 1;
DQ[ Rear ] = X;
}
}
Example: -
A
B
-
C
-
-
-
D
-
0 1
A A
B C B C
1 2 2 3
D E F G D E F G
3 4 5 6 4 5 6 7
A B C D E F G A B C D E F G
0 1 2 3 4 5 6 1 2 3 4 5 6 7
Root = i Root = i
leftchild=2i+1 leftchild=2i
rightchild=2i+2 rightchild=2i+1
Struct treenode
{
int data;
structtreenode *leftchild;
structtreenode *rightchild;
}*T;
T
2000
1000 1 1006
1000 1006
1002 2 1004 1008 5 1010
B C
General Tree:
A General Tree is a tree in which each node can have an unlimited out degree.
Each node may have as many children as is necessary to satisfy its
requirements. Example: Directory Structure
A
B F G
C H I J
It is considered easy to represent binary trees in programs than it is to
represent general trees. So, the general trees can be represented in binary
tree format.
The binary tree format can be adopted by changing the meaning of the left and
right pointers. There are two relationships in binary tree,
Parent to child
Sibling to sibling
Using these relationships, the general tree can be implemented as binary tree.
Algorithm
Identify the branch from the parent to its first or leftmost child. These
branches from each parent become left pointers in the binary tree
Connect siblings, starting with the leftmost child, using a branch for each
sibling to its right sibling.
Remove all unconnected branches from the parent to its children
A
B E F
C D G H I
A A
B E F B E F
C D G H I C D G H I
A
B E F
C B D G H I
Step 3: Delete unneeded branches
C E
D F
G
THE RESULTING BINARY TREE
H
Compared to linear data structures like linked lists and one dimensional array,
which have only one logical means of traversal, tree structures can be
traversed in many different ways. Starting at the root of a binary tree, there
are three main steps that can be performed and the order in which they are
performed defines the traversal type. These steps (in no particular order) are:
performing an action on the current node (referred to as "visiting" the node),
traversing to the left child node, and traversing to the right child node. Thus
the process is most easily described through recursion.
A binary tree traversal requires that each node of the tree be processed once
and only once in a predetermined sequence.
The two general approaches to the traversal sequence are,
Depth first traversal
Breadth first traversal
Breadth-First Traversal
Depth-First Traversal
In depth first traversal, the processing proceeds along a path from the root
through one child to the most distant descendent of that first child before
processing a second child. In other words, in the depth first traversal, all the
descendants of a child are processed before going to the next child.
Inorder--- B A C
Preorder --- A B C
Postorder --- B C A
Inorder Traversal
Steps :
Traverse left subtree in inorder
Process root node
Traverse right subtree in inorder
B E
C D F
The Output is : C B D A E F
Algorithm
Algorithm inoder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Inorder_traversal ( left subtree ( T ) )
Print ( info ( T ) ) / * process node */
Inorder_traversal ( right subtree ( T ) )
End
End
Routines
void inorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
inorder_traversal(T->lchild);
printf( %d \t , T->info);
inorder_traversal(T->rchild);
}
}
Preorder Traversal
Steps :
Process root node
Traverse left subtree in preorder
Traverse right subtree in preorder
Algorithm
Algorithm inoder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Print ( info ( T ) ) / * process node */
Preorder_traversal ( left subtree ( T ) )
Preorder_traversal ( right subtree ( T ) )
End
End
Routines
void inorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
printf( %d \t , T->info);
preorder_traversal(T->lchild);
preorder_traversal(T->rchild);
}
}
B E
Output is : A B C D E F
Postorder Traversal
Steps :
Traverse left subtree in postorder
Traverse right subtree in postorder
process root node
Algorithm
Algorithm postorder traversal (BinTree T)
Begin
If ( not empty (T) ) then
Begin
Postorder_traversal ( left subtree ( T ) )
Postorder_traversal ( right subtree( T))
Print ( Info ( T ) ) / * process node */
End
End
Routines
void postorder_traversal ( NODE * T)
{
if( T ! = NULL)
{
postorder_traversal(T->lchild);
postorder_traversal(T->rchild);
printf( %d \t , T->info);
}
}
B E
C D F
Output is : C D B F E A
A
Examples :
B
C
D E G
F
PREORDER:ABDECFG
3.A BINARY TREE HAS 8 NODES. THE INORDER AND POSTORDER TRAVERSAL OF THE
TREE ARE GIVEN BELOW. DRAW THE TREE AND FIND PREORDER.
POSTORDER: F E C H G D B A
INORDER: FCEABHDG
Answer:
C B
F E D
H
G
PREORDER: ACFEBDHG
Example 4
APPLICATIONS
EXPRESSION TREES
a/b+(c-d)e
Algorithm
1) Examine the next element in the input.
2) If it is an operand, output it.
3) If it is opening parenthesis, push it on stack.
4) If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of the stack is opening parenthesis, push operator on stack.
iii) If it has higher priority than the top of stack, push operator on stack.
iv) Else pop the operator from the stack and output it, repeat step 4.
5) If it is a closing parenthesis, pop operators from the stack and output them
until an opening parenthesis is encountered. pop and discard the opening
parenthesis.
6) If there is more input go to step 1
7) If there is no more input, unstack the remaining operators to output.
Example
Suppose we want to convert 2*3/(2-1)+5*(4-1) into Prefix form: Reversed
Expression: )1-4(*5+)1-2(/3*2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
* +* 23*21-/5
( +*( 23*21-/5
4 +*( 23*21-/54
- +*(- 23*21-/54
1 +*(- 23*21-/541
) +* 23*21-/541-
Empty 23*21-/541-*+
Algorithm
1) Reverse the input string.
2) Examine the next element in the input.
3) If it is operand, add it to output string.
4) If it is Closing parenthesis, push it on stack.
5) If it is an operator, then
Example
/ +/ 14-5*12-
3 +/ 14-5*12-3
* +/* 14-5*12-3
2 +/* 14-5*12-32
Empty 14-5*12-32*/+
Reverse the output string : +/*23-21*5-41 So, the final Prefix Expression is
+/*23-21*5-41
EVALUATION OF EXPRESSIONS
ab+cde+**
The first two symbols are operands, so we create one-node trees and push
pointers to them onto a stack.*
*For convenience, we will have the stack grow from left to right in the
diagrams.
Next, a '+' is read, so two pointers to trees are popped, a new tree is formed,
and a pointer to it is pushed onto the stack.*
Next, c, d, and e are read, and for each a one-node tree is created and a pointer
to the corresponding tree is pushed onto the stack.
Continuing, a '*' is read, so we pop two tree pointers and form a new tree with
a '*' as root.
Finally, the last symbol is read, two trees are merged, and a pointer to the final
tree is left on the stack.
Binary search tree (BST) is a node-based binary tree data structure which
has the following properties:
The left sub-tree of a node contains only nodes with keys less than the
node's key.
The right sub-tree of a node contains only nodes with keys greater than
the node's key.
Both the left and right sub-trees must also be binary search trees.
struct tnode
{
int data;
struct tnode *lchild,*rchild;
};
Normal Tree 2
4 5
7 1
So
2
4
4
5
7
and 1<2 so
2
4
5
1
7
is the final BST.
OPERATIONS
};
Make_null
SEARCH_TREE
make_null ( void )
{
return NULL;
}
Find
T=T-->left;
}
else if(num< T-->data)
{
T=T-->left;
if(num>T-->data)
T=T-->right;
}
if(T-->data==num)
break;
}
return T;
}
// To find a Number
Position find(elementtype X, searchtree T)
{
If(T==NULL)
return NULL;
if(x< T-->element)
return find(x,T-->left);
else if(X> T-->element)
return find(X,T-->right);
else
return T;
}
return NULL;
else if(T-->left==NULL)
return T;
else return findmin(T-->left);
}
// Finding Maximum
Position findmax(searchtree T)
{
if(T==NULL)
return NULL;
else if(T-->right==NULL)
return T;
else return findmin(T-->right);
}
Insert
Figure shows the code for the insertion routine. Since T points to the root of
the tree, and the root changes on the first insertion, insert is written as a
function that returns a pointer to the root of the new tree. Lines 8 and 10
recursively insert and attach x into the appropriate subtree.
{
If(T== NULL)
{
/* create and return a one node tree*/
T=malloc(sizeof(structtreenode));
If(T==NULL)
Fatalerror( Out of Space );
Else
{
T-->element=X;
T-->left=T-->right=NULL;
}
}
Else if(x<T-->element)
T-->left=insert(X,T-->left);
Else if(X>=T-->left)
T-->right=insert(X,T-->right);
Return T;
}
Thus 5 is inserted.
Delete
If the node is a leaf, it can be deleted immediately. If the node has one child,
the node can be deleted after its parent adjusts a pointer to bypass the node
(we will draw the pointer directions explicitly for clarity).. Notice that the
deleted node is now unreferenced and can be disposed of only if a pointer to it
has been saved. The complicated case deals with a node with two children.
The general strategy is to replace the key of this node with the smallest key of
the right subtree (which is easily found) and recursively delete that node
(which is now empty). Because the smallest node in the right subtree cannot
have a left child, the second delete is an easy one.
Case 1:
6 6
2 8 2 8
1 4 1 4
EXAMPLE :
Case 2 :
6 6
2 8 2 8
1 4 1
3 3
Case 3 :
6 6
2 8 3 8
1 4 1 4
5
3 5
EXAMPLE
T=T-->right;
Else if(T-->right==NULL)
T=T-->left;
Free(tmpcell);
}
Return T;
}
Introduction
To count the number of nodes in a given binary tree, the tree is required to be
traversed recursively until a leaf node is encountered. When a leaf node is
encountered, a count of 1 is returned to its previous activation (which is an
activation for its parent), which takes the count returned from both the
children's activation, adds 1 to it, and returns this value to the activation of its
parent. This way, when the activation for the root of the tree returns, it
returns the count of the total number of the nodes in the tree.
Program
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *lchild, *rchild;
};
int count(struct tnode *p)
{
if( p == NULL)
return(0);
else
void main()
{
struct tnode *root = NULL;
int n,x;
printf("Enter the number of nodes\n");
scanf("%d",&n);
while( n --- > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insert(root,x);
}
inorder(root);
printf("\nThe number of nodes in tree are :%d\n",count(root));
}
Explanation
Input:
o 1.The number of nodes that the tree to be created should have
2. The data values of each node in the tree to be created
Output:
o The data value of the nodes of the tree in inorder
2. The count of number of node in a tree.
Example
Input:
o 1.The number of nodes the created tree should have = 5
2. The data values of nodes in the tree to be created are: 10, 20, 5,
9, 8
Output: 1. 5 8 9 10 20
2. The number of nodes in the tree is 5
Introduction
An elegant method of swapping the left and right subtrees of a given binary
tree makes use of a recursive algorithm, which recursively swaps the left and
right subtrees, starting from the root.
Program
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *lchild, *rchild;
};
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts the
newly created node
as left child*/
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
/* a function to binary tree in inorder */
void inorder(struct tnode *p)
{
if(p != NULL)
{
inorder(p->lchild);
printf("%d\t",p->data);
inorder(p->rchild);
}
}
struct tnode *swaptree(struct tnode *p)
{
struct tnode *temp1=NULL, *temp2=NULL;
if( p != NULL)
{ temp1= swaptree(p->lchild);
temp2 = swaptree(p->rchild);
p->rchild = temp1;
p->lchild = temp2;
}
return(p);
}
void main()
{
struct tnode *root = NULL;
int n,x;
printf("Enter the number of nodes\n");
scanf("%d",&n);
while( n - > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insert(root,x);
}
printf("The created tree is :\n");
inorder(root);
printf("The tree after swapping is :\n");
root = swaptree(root);
inorder(root);
printf("\nThe original tree is \n");
root = swaptree(root);
inorder(root);
}
Explanation
Input:
o 1.The number of nodes that the tree to be created should have
2. The data values of each node in the tree to be created
Output:
o 1.The data value of the nodes of the tree in inorder before
interchanging the left and right subtrees
2. The data value of the nodes of the tree in inorder after
interchanging the left and right subtrees
Example
Input:
o 1.The number of nodes that the created tree should have = 5
2. The data values of the nodes in tree to be created are: 10, 20, 5,
9, 8
Output:
o 1. 5 8 9 10 20
2. 20 10 9 8 5
Applications of Trees
1. Compiler Design.
2. Unix / Linux.
3. Database Management.
4. Trees are very important data structures in computing.
5. They are suitable for:
a. Hierarchical structure representation, e.g.,
i. File directory.
ii. Organizational structure of an institution.
iii. Class inheritance tree.
b. Problem representation, e.g.,
i. Expression tree.
ii. Decision tree.
c. Efficient algorithmic solutions, e.g.,
i. Search trees.
ii. Efficient priority queues via heaps.
AVL TREE
The AVL tree is named after its two inventors, G.M. Adelson-Velsky and E.M.
Landis, who published it in their 1962 paper "An algorithm for the
organization of information."
Avl tree is a self-balancing binary search tree. In an AVL tree, the heights of
the two child subtrees of any node differ by at most one; therefore, it is also
said to be height-balanced.
The balance factor of a node is the height of its right subtree minus the
height of its left subtree and a node with balance factor 1, 0, or -1 is
considered balanced. A node with any other balance factor is considered
unbalanced and requires rebalancing the tree. This can be done by avl tree
rotations
The disadvantage of a binary search tree is that its height can be as large
as N-1
This means that the time needed to perform insertion and deletion and
many other operations can be O(N) in the worst case
We want a tree with small height
A binary tree with N node has height at least Q(log N)
Thus, our goal is to keep the height of a binary search tree O(log N)
Such trees are called balanced binary search trees. Examples are AVL
tree, red-black tree.
An AVL tree is a special type of binary tree that is always "partially" balanced.
The criteria that is used to determine the "level" of "balanced-ness" which is
the difference between the heights of subtrees of a root in the tree. The
"height" of tree is the "number of levels" in the tree. The height of a tree is
defined as follows:
The height of an internal node is the maximum height of its children plus 1.
AVL trees are identical to standard binary search trees except that for every
node in an AVL tree, the height of the left and right subtrees can differ by at
most 1 . AVL trees are HB-k trees (height balanced trees of order k) of order
HB-1. The following is the height differential formula:
|Height (Tl)-Height(Tr)|<=k
When storing an AVL tree, a field must be added to each node with one of
three values: 1, 0, or -1. A value of 1 in this field means that the left subtree
has a height one more than the right subtree. A value of -1 denotes the
opposite. A value of 0 indicates that the heights of both subtrees are the same.
EXAMPLE FOR HEIGHT OF AVL TREE
Rotation :
Modification to the tree. i.e. , If the AVL tree is Imbalanced, proper rotations
has to be done.
A rotation is a process of switching children and parents among two or three
adjacent nodes to restore balance to a tree.
Balance Factor :
BF= --1
7
5 12
BF=1 BF= --1
2 10 14
-> RL ( Right -- Left rotation) --- Do single Right, then single Left.
-> LR ( Left -- Right rotation) --- Do single Left, then single Right.
1. LL Rotation :
2. RR Rotation :
EXAMPLE:
LET US CONSIDER INSERTING OF NODES 20,10,40,50,90,30,60,70 in an AVL
TREE
Struct avlnode
Typedef struct avlnode *position;
Typedef structavlnode *avltree;
Typedef int elementtype;
Struct avlnode
{
Elementtype element;
Avltree left;
Avltree right;
Int height;
};
Static int height(position P)
{
If(P==NULL)
return -1;
else
return P-->height;
}
Avltree insert(elementtype X, avltree T)
{
If(T==NULL)
{ / * Create and return a one node tree*/
T= malloc(sizeof(structavlnode));
If(T==NULL)
Fatalerror( Out of Space );
Else
{
T-->element=X;
T-->height=0;
T-->left=T-->right=NULL;
}
}
Else if(X<T-->element)
{
T-->left=Insert(X,T-->left);
If(height(T-->left) - height(T-->right)==2)
If(X<T-->left-->element)
T=singlerotatewithleft(T);
Else
T=doublerotatewithleft(T);
}
Else if(X>T-->element)
{
T-->right=insert(X,T-->right);
If(height(T-->left) - height(T-->right)==2)
If(X>T-->right-->element)
T= singlerotatewithright(T);
Else
T= doublerotatewithright(T);
}
T-->height=max(height(T-->left),height(T-->right)) + 1;
Return T;
}
{
Position k1;
k1=k2-->left;
k2-->left=k1-->right;
k1-->right=k2;
k2-->height= max(height(k2-->left),height(k2-->right)) + 1;
k1-->height= max(height(k1-->left),height(k1-->right)) + 1;
return k1; / * New Root * /
}
PROBLEMS
APPLICATIONS
AVL trees play an important role in most computer related applications. The
need and use of avl trees are increasing day by day. their efficiency and less
complexity add value to their reputation. Some of the applications are
AVL trees guarantee that the difference in height of any two subtrees
rooted at the same node will be at most one. This guarantees an
asymptotic running time of O(log(n)) as opposed to O(n) in the case of a
standard bst.
Height of an AVL tree with n nodes is always very close to the
theoretical minimum.
Since the avl tree is height balabced the operation like insertion and
deletion have low time complexity.
BINARY HEAPS
it is empty or
the key in the root is larger than that in either child and both subtrees
have the heap property.
Structure Property :
COMPLETE TREE
A binary tree is completely full if it is of height, h, and has 2h+1-1 nodes.
it is empty or
its left subtree is complete of height h-1 and its right subtree is
completely full of height h-2 or
its left subtree is completely full of height h-1 and its right subtree is
complete of height h-1.
PROCEDURE
INSERTION:
DELETION:
PRIORITY QUEUE
Deletion(h) I
Priority Queue Insertion(h)
Linked List :
A simple linked list implementation of priority queue requires o(1) time
to perform the insertion at the front and o(n) to delete at minimum element.
1.Structure Property :
The Heap should be a complete binary tree, which is a completely filled
tree, which is a completely filled binary tree with the possible exception of the
bottom level, which is filled from left to right.
A Complete Binary tree of height H, has between 2h and (2h+1 - 1) nodes.
Sentinel Value :
The zeroth element is called the sentinel value. It is not a node of the tree.
This value is required because while addition of new node, certain operations
are performed in a loop and to terminate the loop, sentinel value is used.
Index 0 is the sentinel value. It stores irrelated value, inorder to terminate the
program in case of complex codings.
Structure Property : Always index 1 should be starting position.
Mintree:
Parent should have lesser value than children.
Maxtree:
Parent should have greater value than children.
Max-heap
Min-heap
Min-heap:
The smallest element is always in the root node.Each node must have a
key that is less or equal to the key of each of its children.
Examples
Max-Heap:
The largest Element is always in the root node.
Each node must have a key that is greater or equal to the key of each of its
children.
Examples
HEAP OPERATIONS:
There are 2 operations of heap
Insertion
Deletion
2.12.1 Insert:
Adding a new key to the heap
Example Problem :
2. Insert the keys 4, 6, 10, 20, and 8 in this order in an originally empty max-
heap
EXAMPLE PROBLEMS :
1.DELETE MIN
2. Delete Min -- 13
elementtype *element;
};
Insert Routine
For(i=++H-->size;H-->elements[i/2]>X;i=i/2)
H-->elements[i]=H-->elements[i/2];
H-->elements[i]=X;
}
Delete Routine
Elementtype deletemin(priorityqueue H)
{
int i,child;
elementtype minelement,lastelement;
if(isempty(H))
{
Error( Priority queue is empty );
Return H-->element[0];
}
Minelement=H-->element[1];
Lastelement=H-->element[H-->size--];
For(i=1;i*2<=H-->size;i=child)
{
/ *Find smaller child */
Child=i*2;
If(child!=H-->size && H-->elements[child++]<H-->elements[child])
{
Child++;
}
/ * Percolate one level * /
If(lastelement>H-->elements[child])
H-->element[i]=H-->elements[child];
Else
Break;
}
H-->element[i]=lastelement;
Return minelement;
}
1. Decrease Key.
2. Increase Key.
3. Delete.
4. Build Heap.
1.Decrease Key :
10 10 8
15 12 8 12 10 12
20 30 20 30 20 30
2.Increase Key :
10 10 10
12 22 12
15 20 12
20 30 20 30
22 30
3. Delete :
The delete(P,H) operation removes the node at the position P, from the heap
H. This can be done by,
20
12 -∞ 12
10 12
22 30 22 30
22 30
Step 2 : Deletemin(H)
10 10
12 12
10 22 12
20 20
30
APPLICATIONS
Heap sort
Selection algorithms
Graph algorithms
Heap sort :
One of the best sorting methods being in-place and with no quadratic
worst-case scenarios.
Selection algorithms:
Finding the min, max, both the min and max, median, or even the k-th
largest element can be done in linear time using heaps.
Graph algorithms:
By using heaps as internal traversal data structures, run time will be
reduced by an order of polynomial. Examples of such problems are Prim's
minimal spanning tree algorithm and Dijkstra's shortest path problem.
ADVANTAGE
It is used in
o Heap sort
o Selection algorithms
o Graph algorithms
DISADVANTAGE
safety
maintenance
performance
Performance :
Allocating heap memory usually involves a long negotiation with the OS.
Maintenance:
Dynamic allocation may fail; extra code to handle such exception is
required.
Safety :
Object may be deleted more than once or not deleted at all .
B-TREES
Multi-way Tree
A B-tree of order m (or branching factor m), where m > 2, is either an empty
tree or a multiway search tree with the following properties:
The root is either a leaf or it has at least two non-empty subtrees
and at most m non-empty subtrees.
Each non-leaf node, other than the root, has at least m/2 non-
empty subtrees and at most m non-empty subtrees. (Note: x is the
lowest integer > x ).
The number of keys in each non-leaf node is one less than the
number of non-empty subtrees for that node.
All leaf nodes are at the same level; that is the tree is perfectly
balanced.
Insertion in B-Trees
OVERFLOW CONDITION:
A root-node or a non-root node of a B-tree of order m overflows if, after a
key insertion, it contains m keys.
Insertion algorithm:
If a node overflows, split it into two, propagate the "middle" key to the
parent of the node. If the parent overflows the process propagates upward. If
the node has no parent, create a new root node.
• Note: Insertion of a key always starts at a leaf node.
Example: Insert the keys 78, 52, 81, 40, 33, 90, 85, 20, and 38 in this order in
an initially empty B-tree of order 3
ADVANTAGES:
• B-trees are suitable for representing huge tables residing in secondary
memory because:
1. With a large branching factor m, the height of a B-tree is low
resulting in fewer disk accesses.
2. The branching factor can be chosen such that a node corresponds
to a block of secondary memory.
3. The most common data structure used for database indices is the B-
tree. An index is any data structure that takes as input a property
(e.g. a value for a specific field), called the search key, and quickly
finds all records with that property.
Note: As m increases the amount of computation at each node increases;
however this cost is negligible compared to hard-drive accesses.
Application of graphs:
Coloring of MAPS
Representing network
o Paths in a city
o Telephone network o
Electrical circuits etc.
It is also using in social network
including o LinkedIn
o Facebook
Types of Graphs:
Directed graph
Undirected Graph
Directed Graph:
In representing of graph there is a directions are
shown on the edges then that graph is called
Directed graph.
That is,
A graph G=(V, E) is a directed graph ,Edge is a
pair (v, w), where v, w ∈ V, and the pair is ordered.
Means vertex ‘w’ is adjacent to v.
Directed graph is also called digraph.
Undirected Graph:
In graph vertices are not ordered is called undirected
graph. Means in which (graph) there is no direction
(arrow head) on any line (edge).
A graph G=(V, E) is a directed graph ,Edge is a pair
Weight graph:
Edge may be weight to show that there is
a cost to go from one vertex to another.
Example: In graph of roads (edges) that
connect one city to another (vertices), the
weight on the edge might represent the
distance between the two cities (vertices).
n=3 3 n=7 21
n=4 6 n=5 10
Sub graph:
A sub-graph G' of graph G is a graph, such that the set of vertices and set of edges
of G' are proper subset of the set of vertices and set of edges of graph G
respectively.
Connected Graph:
A graph which is connected in the sense of a topological space ( study of shapes), i.e., there is
a path from any point to any other point in the graph. A graph that is not connected is said to
be disconnected.
Path:
A path in a graph is a finite or infinite sequence of edges which connect a sequence of
vertices. Means a path form one vertices to another vertices in a graph is represented by
collection of all vertices (including source and destination) between those two vertices.
Simple Cycle: a cycle that does not pass through other vertices more than once
Degree:
The degree of a graph vertex v of a graph G is the number of graph edges which touch v. The
vertex degree is also called the local degree or valency. Or
The degree (or valence) of a vertex is the number of edge ends at that vertex.
For example, in this graph all of the vertices have degree three.
In a digraph (directed graph) the degree is usually divided into the in-degree and the out-
degree
In-degree: The in-degree of a vertex v is the number of edges with v as their terminal
vertex.
Out-degree: The out-degree of a vertex v is the number of edges with v as their initial
vertex.
TOPOLOGICAL SORT
A topological sort is a linear ordering of vertices in a Directed Acyclic Graph
such that if there is a path from Vi to Vp, then Vj appears after Vi in the linear
ordering.Topological sort is not possible if the graph has a cycle.
INTRODUCTION
PROCEDURE
Step – 3 : Dequeue the vertex V and decrement the indegrees of all its adjacent
vertices.
Step – 4 : Enqueue the vertex on the queue if its indegree falls to zero.
Vertices Indegree
1 0
2 0
GRAPH TRAVERSAL
Graph traversal is the Visiting all the nodes of a graph.
The Breadth first search was one of the systematic approaches for
exploring and searching the vertices/nodes in a given graph. The
approach is called "breadth-first" because from each vertex v that we
visit, we search as broadly as possible by next visiting all the vertices
adjacent to v.
It can also be used to find out whether a node is reachable from a given
node or not.
It is applicable to both directed and undirected graphs.
Queue is used in the implementation of the breadth first search.
ALGORITHM
Procedure bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove(); Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
Procedure
Step -1 Select the start vertex/source vertex. Visit the vertex and mark it
as one (1) (1 represents visited vertex).
Step -2 Enqueue the vertex.
Step -3 Dequeue the vertex.
Step -4 Find the Adjacent vertices.
Step -5 Visit the unvisited adjacent vertices and mark the distance as 1.
Step -6 Enqueue the adjacent vertices.
Step -7 Repeat from Step – 3 to Step – 5 until the queue becomes empty.
Ex : A B Vertices Visited
Vertices
A 1
C D B 0 1
C 0 1
D 0 1
Enqueue A B C D
Dequeue A B C D
A B
Vertices Visited
Vertices
C 1
C D A 0 1
B 0 1
D 0 1
E E 0 1
Enqueue C A B D
E
Dequeue C A B D
E
Pseudo Code :
void BFS(Vertex S)
Vertex v,w;
Queue Q;
visited[s] = 1; enqueue(S,Q);
while(!IsEmpty(a))
v = Dequeue(Q);
print(v);
if(visited[w]==0)
visited[w] = 1;
Enqueue(w,Q);
APPLICATIONS
Breadth-first search can be used to solve many problems in graph theory, for
example.
Uses
In DFS, the basic data structures for storing the adjacent nodes is stack.
Procedure:
Pseudo Code:
void DFS(Vertex S)
int top = 0;
visited [S] = 1
C[top] = S;
while(!IsEmpty(C))
v = pop(C);
print(V);
if(visited[w] == 0)
visited[w] = 1;
push(w,C);
(OR)
void DFS(vertex V)
visited[v] = 1;
push(v);
pop(v);
if(!visited[w])
Dfs(w);
ALGORITHM
Procedure dfs()
{
//DFS uses Stack data structure
Stack s=new Stack();
s.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode);
while(!s.isEmpty())
{
Node n=(Node)s.peek();
Node child=getUnvisitedChildNode(n);
if(child!=null)
{
child.visited=true;
printNode(child);
s.push(child);
}
else
{
s.pop();
}
}
//Clear visited property of nodes
clearNodes();
}
Applications of DFS :
I. Undirected Graph :
An undirected graph is connected if and only if a depth first search
starting from any node visits every node.
A 1. Tree Edge
B D E
A A
C B B
C E C
D D
B A C
G B
C D A
F D
G E F
E
A
C D
G E
II. Bi-Connectivity :
B A A (1,1)
B (2,1)
C D (3,1) C G (7,7)
F D (4,1)
G E E (5,4)
F (6,4)
BICONNECTIVITY :
A connected undirected graph is biconnective if there are no vertices
whose removal disconnects the rest of the graph.
DEFINITION
containing u and v.
Biconnected Components
Articulation Point :
The root is an articulation if and only if (iff) it has more than two children.
Any vertex V other than the root is an Articulation point iff V has some child W
such that Low(W)≥Num (V)
A (1,1)
B (2,1)
C (3,1)
D (4,1) G (7,7)
E (5,4)
F (6,4)
= min(6, 4, -1)
=4
Low(E) = min(5, 6, 4)
=4
Low(D) = min(4, 1, 4)
=1
Low(G) = min(7, -, -)
=7
=1
Low(B) = min(2, 3, 1)
=1
Low(A) = min(1, 2, 1)
=1
Example 2
B E H I
A C F I K
A F
D G E
Visited Parent[]
1 2 3 4
1 1 1 1 1 1 1 1
A B C D 0 1 2 3
0 1 2 3
1 1 1 1
Num[] A B C D
A A (1,1)
B C B (2,1)
D C (3,1)
D (4,4)
ALGORITHM
void AssignNum(Vertex V)
{
Vertex W;
int counter = 0;
Num[V] = ++counter;
visited[V] = True;
for each W adjacent to V
if(!visited[W])
{
parent[W] = V;
AssignNum(W);
}
}
void AssignLow(Vertex V)
{
Vertex W;
Low[V] = Num[V]; /* Rule 1 */
for each W adjacent to V
{
if(Num[W] > Num[V]) /* forward edge or free edge */
{ AssignLow(W)
if(low[W] >= Num[V])
printf( %v Articulation point is , V);
Low[V] = min(Low[V], Low[W]); /* Rule 3 */
}
else
{
if(parent[V]! = W) /* Back edge */
Low[V] = min(Low[V], Num[W]); /* Rule 2 */
}
}
}
APPLICATION
BICONNECTIVITY ADVANTAGES
DISADVANTAGES
EULER CIRCUIT
EULERIAN PATH
EULERIAN CIRCUIT
Unicursal. While such graphs are Eulerian graphs, not every Eulerian graph
possesses an Eulerian cycle.
EULER'S THEOREM
Euler's theorem 1
If a graph has any vertex of odd degree then it cannot have an Euler
circuit.
If a graph is connected and every vertex is of even degree, then it at least
has one Euler circuit.
Euler's theorem 2
If a graph has more than two vertices of odd degree then it cannot have
an Euler path.
If a graph is connected and has just two vertices of odd degree, then it at
least has one Euler path. Any such path must start at one of the odd-
vertices and end at the other odd vertex.
ALGORITHM
1. Check to make sure that the graph is connected and all vertices are of
even degree
2. Start at any vertex
3. Travel through an edge:
o If it is not a bridge for the untraveled part, or
o there is no other alternative
4. Label the edges in the order in which you travel them.
5. When you cannot travel any more, stop.
Fleury's Algorithm
the original graph minus the darkened (already used) edges = reduced
graph
important rule: never cross a bridge of the reduced graph unless there is
no other choice
Note:
APPLICATION
IMPORTANT SUMS
1. Topological Sort
V2 V3 VerticesIndegree
V1 0
V2 1 0
V3 1 0 0
V1 V4 V5 V6 V10
V4 1 0
V5 1 0
V6 2 1 0
V7 V8 V9 V7 2 1
0
V8 1 0
V9 1 0
V10 1 0
Enqueue V1 V2 V4 V3 V5 V10 V6
V9 V8 V7
Sorted Vertices : Dequeue V1 V2 V4 V3 V5 V10 V6
V9 V8 V7
V1 V2 V4 V3 V5 V10 V6 V9 V8 V7
b c
2
a d
6
6 4
f e
void Topsort(Graph G)
Queue Q;
Make Empty(Q);
if (Indegree[V]==0)
enqueue(V,Q);
while(!Isempty(Q))
V = Dequeue(Q);
Topnum[V]=++Counter;
if(--Indegree[w]==0)
Enqueue(w,0);
if(counter!=Num Vertex)
Dispose Queue(Q);
void unweighted(Table T)
Queue Q;
Vertex v,w;
Make Empty(Q);
while(!IsEmpty(Q))
V = Dequeue(o);
T[V].Known = True;
if(!T[w].Known)
if(!T[w].Known)
/* update of w */
T[w].path = v;
Dispose Queue(Q);
SORTING:
Definition:
Sorting is a technique for arranging data in a particular order.
Order of sorting:
Order means the arrangement of data. The sorting order can be ascending or descending. The
ascending order means arranging the data in increasing order and descending order means
arranging the data in decreasing order.
Types of Sorting
Internal Sorting
External Sorting
Internal Sorting
Internal Sorting is a type of sorting technique in which data resides on main memory of
computer. It is applicable when the number of elements in the list is small.
E.g. Bubble Sort, Insertion Sort, Shell Sort, Quick Sort., Selection sort, Radix sort
External Sorting
External Sorting is a type of sorting technique in which there is a huge amount of data and it resides on
secondary devise(for eg hard disk,Magnetic tape and so no) while sorting.
E.g. Merge Sort, Multiway Merge Sort,Polyphase merge sort
Sorting can be classified based on
1.Computational complexity
2.Memory utilization
3.Stability
4.Number of comparisons.
ANALYSIS OF ALGORITHMS:
Efficiency of an algorithm can be measured in terms of:
Sorting algorithms:
Insertion sort
Selection sort
Shell sort
Bubble sort
Quick sort
Merge sort
Radix sort
INSERTION SORTING:
The insertion sort works by taking elements from the list one by one and inserting them
in the correct position into a new sorted list.
Insertion sort consists of N-1 passes, where N is the number of elements to be sorted.
The ith pass will insert the ith element A[i] into its rightful place among
A[1],A[2],…,A[i-1].
After doing this insertion the elements occupying A[1],…A[i] are in sorted order.
}
a[j]=temp;
}}
Program for Insertion sort
#include<stdio.h>
void main( ){
int n, a[ 25 ], i, j, temp;
printf( "Enter number of elements \n" );
scanf( "%d", &n );
printf( "Enter %d integers \n", n );
for ( i = 0; i < n; i++ )
scanf( "%d", &a[i] );
for ( i = 0 ; i < n; i++ ){
temp=a[i];
for (j=i;j > 0 && a[ j -1]>temp;j--)
{
a[ j ] = a[ j - 1 ];
}
a[j]=temp;}
printf( "Sorted list in ascending order: \n ");
for ( i = 0 ; i < n ; i++)
printf ( "%d \n ", a[ i ] );}
OUTPUT:
Enter number of elements
6
Enter 6 integers
20 10 60 40 30 15
Sorted list in ascending order:
10
15
20
30
40
60
Advantage of Insertion sort
Simple implementation.
Efficient for (quite) small data sets.
Efficient for data sets that are already substantially sorted.
Selection sort selects the smallest element in the list and place it in the first position then selects
the second smallest element and place it in the second position and it proceeds in the similar way
until the entire list is sorted. For “n” elements, (n-1) passes are required. At the end of the ith
iteration, the ith smallest element will be placed in its correct position.
for ( i = k ; i < n ; i ++ )
{
temp = a [ i ] ;
for (j = i ; j>= k && a [ j - k ]>temp ; j=j - k )
{
a[j]=a[j-k];
}
a [ j ] = temp ;
}
}
printf( "Sorted list in ascending order using shell sort: \n ");
for ( i = 0 ; i < n ; i++)
printf ( "%d\t ", a[ i ] );
}
OUTPUT:
Enter number of elements
10
Enter 10 integers
81 94 11 96 12 35 17 95 28 58
Sorted list in ascending order using shell sort:
11 12 17 28 35 58 81 94 95 96
//PROGRAM FOR SHELL USING FUNCTION
#include < stdio.h >
void main( )
{
int a [ 5 ] = { 4, 5, 2, 3, 6 } , i = 0 ;
ShellSort ( a, 5 ) ;
printf(“Example using function”);
printf( " After Sorting :" ) ;
for ( i = 0 ; i < 5 ; i ++ )
printf ( " %d ", a[ i ] ) ;
}
void ShellSort (int a [ 5 ] , int n )
{
int i , j , k , temp ;
for ( k = n / 2 ; k > 0 ; k / = 2)
{
for ( i = k ; i < n ; i ++ )
{
temp = a [ i ] ;
for ( j = i ; j > = k && a [ j – k ] > temp ; j = j – k ){
a[j]=a[j–k];
}
a [ j ] = temp ; } }}
OUTPUT:
After Sorting : 2 3 4 5 6
Advantages of Shell sort
• Efficient for medium-size lists.
Disadvantages of Shell sort
• Complex algorithm, not nearly as efficient as the merge, heap and quick sorts
Bubble Sort
Bubble sort is one of the simplest internal sorting algorithms.
Bubble sort works by comparing two consecutive elements and the largest element
among these two bubbles towards right at the end of the first pass the largest element gets
sorted and placed at the end of the sorted list.
This process is repeated for all pairs of elements until it moves the largest element to the
end of the list in that iteration.
Bubble sort consists of (n-1) passes, where n is the number of elements to be sorted.
In 1st pass the largest element will be placed in the nth position.
In 2nd pass the second largest element will be placed in the (n-1)th position.
In (n-1)th pass only the first two elements are compared.
1.
Assume A[0]=pivot which is the left. i.e pivot=left.
2.
Set i=left+1; i.e A[1];
3.
Set j=right. ie. A[6] if there are 7 elements in the array
4.
If A[pivot]>A[i],increment i and if A[j]>A[pivot],then decrement j, Otherwise swap A[i]
and A[j] element.
5. If i=j,then swap A[pivot] and A[j].
#include<stdio.h>
void quicksort (int [10], int, int ) ;
void main( )
{
int a[20], n, i ;
printf("Enter size of the array:" );
scanf("%d",&n);
printf( " Enter the numbers :");
for ( i = 0 ; i < n ; i ++ )
scanf ("%d",&a[i]);
quicksort ( a , 0 , n - 1 );
printf ( " Sorted elements: " );
for ( i = 0 ; i < n ; i ++ )
printf ("%d\t",a[ i]);
}
OUTPUT:
Enter size of the array:8
Merge Sort
Merge sort is a sorting algorithm that uses the divide, conquer, and combine algorithmic
paradigm.
Divide means partitioning the n-element array to be sorted into two sub-arrays of n/2 elements.
If there are more elements in the array, divide A into two sub-arrays, A1 and A2, each containing
about half of the elements of A.
Conquer means sorting the two sub-arrays recursively using merge sort.
Combine means merging the two sorted sub-arrays of size n/2 to produce the sorted array of n
elements.
The basic steps of a merge sort algorithm are as follows:
If the array is of length 0 or 1, then it is already sorted.
Otherwise, divide the unsorted array into two sub-arrays of about half the size.
Use merge sort algorithm recursively to sort each sub-array.
Merge the two sub-arrays to form a single sorted list.
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j);
//right recursion merge(a,i,mid,mid+1,j); //merging of two
sorted sub-arrays
}}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{ if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
OUTPUT:
Enter no of elements:8
Enter array elements:24 13 26 1 2 27 38 15
Sorted array is :1 2 13 15 24 26 27 38
Advantages of Merge sort
• Mergesort is well-suited for sorting really huge amounts of data that does not fit into
memory.
• It is fast and stable algorithm
Radix Sort
Radix sort is one of the linear sorting algorithms. It is generalized form of bucket sort. It
can be performed using buckets from 0 to 9.
It is also called binsort, card sort.
It works by sorting the input based on each digit. In first pass all the elements are stored
according to the least significant digit.
In second pass the elements are arranged according to the next least significant digit and
so on till the most significant digit.
The number of passes in a Radix sort depends upon the number of digits in the given
numbers.
Step2: Consider the LSB (Least Significant Bit) of each number (numbers in the one‟s
Step3: Place the elements in their respective buckets according to the LSB of each number
Step5: repeat the same process with the digits in the 10‟s place (e.g. In 43 MSB =4)
Step6: repeat the same step till all the digits of the given number are consider.
large = large / 10 ;
}
for ( passes = 0 ; passes < num ; passes ++ )
{
for ( k = 0 ; k < 10 ; k ++ )
{
buck [ k ] = 0 ;
}
for ( i = 0 ; i < n ; i ++ )
{
l = ( ( a [ i ] / div ) % 10 ) ;
bucket [ l ] [ buck [ l ] ++ ] = a [ i ] ;
}
i=0;
for ( k = 0 ; k < 10 ; k ++ )
{
for ( j = 0 ; j < buck [ k ] ; j ++ )
{
a [ i ++ ] = bucket [ k ] [ j ] ;
}
}
div * = 10 ;
}
}
}
#include<stdio.h >
void main( )
{
int a [ 5 ] = { 4, 5, 2, 3, 6 } , i = 0 ;
void Radix_sort ( int a [ ] , int n );
Radix_sort(a,5);
printf( " After Sorting :" ) ;
for ( i = 0 ; i < 5 ; i ++ )
printf ( " %d ", a[ i ] ) ;
}
void Radix_sort ( int a [ ] , int n )
{
int bucket [ 10 ] [ 5 ] , buck [ 10 ] , b [ 10 ] ;
int i , j , k , l , num , div , large , passes ;
div = 1 ;
num = 0 ;
large = a [ 0 ] ;
for ( i = 0 ; i < n ; i ++ ){
if ( a[ i] > large )
{
large = a [ i ] ;
}
while ( large > 0 )
{
num ++ ;
large = large / 10 ;
}
for ( passes = 0 ; passes < num ; passes ++ )
{
for ( k = 0 ; k < 10 ; k ++ )
{
buck [ k ] = 0 ;
}
for ( i = 0 ; i < n ; i ++ )
{
l = ( ( a [ i ] / div ) % 10 ) ;
bucket [ l ] [ buck [ l ] ++ ] = a [ i ] ;
}
i=0;
for ( k = 0 ; k < 10 ; k ++ )
{
for(j=0 ; j<buck[k];j++ )
{
a[i++]=bucket[ k ][ j ] ;
}
}
div*= 10 ;
}
}
}
SEARCHING
Searching is an algorithm, to check whether a particular element is present in the list.
Types of searching:-
Linear search
Binary Search
Linear Search
Linear search is used to search a data item in the given set in the sequential manner, starting from
the first element. It is also called as sequential search
count ++ ;
}
if ( count = = 0 )
printf( " \n Element %d is not present in the array " , search ) ;
else
printf ( " \n Element %d is present %d times in the array \n " , search , count ) ;
}
OUTPUT:
Enter the number of elements 5
Enter the numbers
20 10 5 25 100
Array Elements
20 10 5 25 100
Enter the Element to be searched: 25
Element 25 is present 1 times in the array
Binary Search
Binary search is used to search an item in a sorted list. In this method , initialize the lower
limit and upper limit.
The middle position is computed as (first+last)/2 and check the element in the middle
position with the data item to be searched.
If the data item is greater than the middle value then the lower limit is adjusted to one
greater than the middle value.Otherwise the upper limit is adjusted to one less than the
middle value.
Working principle:
Algorithm is quite simple. It can be done either recursively or iteratively:
1. Get the middle element;
2. If the middle element equals to the searched value, the algorithm stops;
3. Otherwise, two cases are possible:
o Search value is less than the middle element. In this case, go to the step 1 for the
part of the array, before middle element.
o Searched value is greater, than the middle element. In this case, go to the step 1
for the part of the array, after middle element.
Example 1.
last = mid – 1 ;
mid = ( first + last ) / 2 ;
}
if( first > last )
print “Element Not Found” ;
}
Program for Binary Search:
#include<stdio.h>
void main( )
{
int a [ 10 ] , n , i , search, count = 0 ;
void Binary_search ( int a[ ] , int n , int search );
printf ("Enter the number of elements \t") ;
scanf ("%d",&n);
printf("\nEnter the numbers\n") ;
for (i = 0; i<n;i++)
scanf("%d",&a[i]);
printf("\nArray Elements\n") ;
for (i = 0 ; i < n ; i ++ )
printf("%d\t",a[i]) ;
printf ("\n\nEnter the Element to be searched:\t");
scanf("%d",&search );
Binary_search(a,n,search);
}
void Binary_search ( int a[ ] , int n , int search )
{
int first, last, mid ;
first = 0 ;
last = n-1 ;
mid = (first + last ) / 2 ;
while (first<=last )
{
if(search>a[mid])
first = mid + 1 ;
else if (search==a[mid])
{
printf("Element is present in the list");
break ;
}
else
last = mid - 1 ;
mid = ( first + last ) / 2 ;
}
if( first > last )
printf("Element Not Found");
}
OUTPUT:
Enter the number of elements 5
Enter the numbers
20 25 50 75 100
Array Elements
20 25 50 75 100
Enter the Element to be searched: 75
Element is present in the listPress any key to continue . . .
Advantages of Binary search:
In Linear search, the search element is compared with all the elements in the array. Whereas
in Binary search, the search element is compared based on the middle element present in the
array.
A technique for searching an ordered list in which we first check the middle item and - based
on that comparison - "discard" half the data. The same procedure is then applied to the
remaining half until a match is found or there are no more items left.
Disadvantages of Binary search:
Binary search algorithm employs recursive approach and this approach requires more
stack space.
It requires the data in the array to be stored in sorted order.
It involves additional complexity in computing the middle element of the array.
Analysis Analysis
1 Linear search O(1) O(N) O(N)
2 Binary search O(1) O(log N) O(log N)
HASHING :
Hashing is a technique that is used to store, retrieve and find data in the data structure
called Hash Table. It is used to overcome the drawback of Linear Search (Comparison) &
Binary Search (Sorted order list). It involves two important concepts-
Hash Table
Hash Function
Hash table
A hash table is a data structure that is used to store and retrieve data (keys) very
quickly.
It is an array of some fixed size, containing the keys.
Hash table run from 0 to Tablesize – 1.
Each key is mapped into some number in the range 0 to Tablesize – 1.
This mapping is called Hash function.
Insertion of the data in the hash table is based on the key value obtained from the
hash function.
Using same hash key value, the data can be retrieved from the hash table by few
or more Hash key comparison.
The load factor of a hash table is calculated using the formula:
(Number of data elements in the hash table) / (Size of the hash table)
Hash function
Table size.
Collision handling scheme
0
1
2
3
.
. Simple Hash table with table size = 10
8
9
Hash function:
It is a function, which distributes the keys evenly among the cells in the Hash
Table.
Using the same hash function we can retrieve data from the hash table.
Hash function is used to implement hash table.
The integer value returned by the hash function is called hash key.
If the input keys are integer, the commonly used hash function is
E.g. consider the following data or record or key (36, 18, 72, 43, 6) table size = 8
93 44
3306 107
4999
The folding method for constructing hash functions begins by dividing the item into
equal-size pieces (the last piece may not be of equal size). These pieces are then added together
to give the resulting hash key value. For example, if our item was the phone number 436-555-
4601, we would take the digits and divide them into groups of 2 (43, 65, 55, 46, 01). After the
addition, 43+65+55+46+01, we get 210. If we assume our hash table has 11 slots, then we need
to perform the extra step of dividing by 11 and keeping the remainder. In this case 210 % 11 is 1,
so the phone number 436-555-4601 hashes to slot 1.
6-555-4601
Collision:
If two more keys hashes to the same index, the corresponding records cannot be stored in the
same location. This condition is known as collision.
Characteristics of Good Hashing Function:
P = find ( key, H );
if(P = = NULL)
{
newnode = malloc(sizeof(Struct node));
L = H TheLists[Hash(key,Tablesize)];
newnode nex t= L next;
newnode data = key;
L next = newnode;
}}
Position find( int key, Hashtable H){
Position P, List L;
L = H TheLists[Hash(key,Tablesize)];
P = L next;
while(P != NULL && P data != key)
P = P next;
return P;}
If two keys map to same value, the elements are chained together.
Initial configuration of the hash table with separate chaining. Here we use SLL(Singly Linked List)
concept to chain the elements.
NULL
0
NULL
1
NULL
2
NULL
3
NULL
4
NULL
5
NULL
6
NULL
7
NULL
8
NULL
9
Insert the following four keys 22 84 35 62 into hash table of size 10 using separate chaining.
The hash function is
H(key) = key % 10
1. H(22) = 22 % 10 =2 2. 84 % 10 = 4
3.H(35)=35%10=5 4. H(62)=62%10=2
Advantages
1. More number of elements can be inserted using array of Link List
Disadvantages
1. It requires more pointers, which occupies more memory space.
2.Search takes time. Since it takes time to evaluate Hash Function and also to traverse the
List
Open Addressing
Closed Hashing
Collision resolution technique
Uses Hi(X)=(Hash(X)+F(i))mod Tablesize
When collision occurs, alternative cells are tried until empty cells are found.
Types:-
Linear Probing
Quadratic Probing
Double Hashing
Hash function
H(key) = key % table size.
Insert Operation
To insert a key; Use the hash function to identify the list to which the
element should be inserted.
Then traverse the list to check whether the element is already present.
If exists, increment the count.
Else the new element is placed at the front of the list.
Linear Probing:
Easiest method to handle collision.
Apply the hash function H (key) = key % table size
Hi(X)=(Hash(X)+F(i))mod Tablesize,where F(i)=i.
How to Probing:
first probe – given a key k, hash to H(key)
second probe – if H(key)+f(1) is occupied, try H(key)+f(2)
And so forth.
Probing Properties:
We force f(0)=0
The ith probe is to (H (key) +f (i)) %table size.
If i reach size-1, the probe has failed.
Depending on f (i), the probe may fail sooner.
Long sequences of probe are costly.
Probe Sequence is:
H (key) % table size
H (key)+1 % Table size
H (Key)+2 % Table size
EMPTY 89 18 49 58 69
0 49 49 49
1 58 58
2 69
3
4
5
6
7
8 18 18 18
9 89 89 89 89
Linear probing
Quadratic Probing
To resolve the primary clustering problem, quadratic probing can be used. With quadratic
probing, rather than always moving one spot, move i2 spots from the point of collision, where
i is the number of attempts to resolve the collision.
Another collision resolution method which distributes items more evenly.
From the original index H, if the slot is filled, try cells H+12, H+22, H+32,.., H + i2 with
wrap-around.
Hi(X)=(Hash(X)+F(i))mod Tablesize,F(i)=i2
Hi(X)=(Hash(X)+ i2)mod Tablesize
Limitation: at most half of the table can be used as alternative locations to resolve collisions.
This means that once the table is more than half full, it's difficult to find an empty spot. This
new problem is known as secondary clustering because elements that hash to the same hash
key will always probe the same alternative cells.
Double Hashing
Double hashing uses the idea of applying a second hash function to the key when a
collision occurs. The result of the second hash function will be the number of positions forms
the point of collision to insert.
There are a couple of requirements for the second function:
It must never evaluate to 0 must make sure that all cells can be probed.
Hi(X)=(Hash(X)+i*Hash 2(X))mod Tablesize
A popular second hash function is:
Hash2 (key) = R - (key % R) where R is a prime number that is smaller than the size of the
table.
Rehashing
Once the hash table gets too full, the running time for operations will start to take too
long and may fail. To solve this problem, a table at least twice the size of the original will be
built and the elements will be transferred to the new table.
Advantage:
A programmer doesn‟t worry about table system.
Simple to implement
Can be used in other data structure as well
The new size of the hash table:
should also be prime
will be used to calculate the new insertion spot (hence the name rehashing)
This is a very expensive operation! O(N) since there are N elements to rehash and the
table size is roughly 2N. This is ok though since it doesn't happen that often.
The question becomes when should the rehashing be applied?
Some possible answers:
once the table becomes half full
once an insertion fails
once a specific load factor has been reached, where load factor is the ratio of the
number of elements in the hash table to the table size
Extendible Hashing
Extendible Hashing is a mechanism for altering the size of the hash table to accommodate
new entries when buckets overflow.
Common strategy in internal hashing is to double the hash table and rehash each entry.
However, this technique is slow, because writing all pages to disk is too expensive.
Therefore, instead of doubling the whole hash table, we use a directory of pointers to
buckets, and double the number of buckets by doubling the directory, splitting just the
bucket that overflows.
Since the directory is much smaller than the file, doubling it is much cheaper. Only one
page of keys and pointers is split.
000 100 0 1
010 100
100 000
111 000 000 100 100 000
001 000 010 100 111 000
011 000 001 000 101 000
101 000 011 000 111 001
111 001
001 010 00 01 10 11
101 100
101 110
UNIT - 1
PART – A
1. Should arrays or linked lists be used for the following types of applications: - Justify your
answer.
a. Many search operations in sorted list
In this case, using arrays will save time because there will be fewer
comparisons. Since the list is sorted the key value can be compared with the middle
element of the array and if the key < array element, then left part of array should be
searched; if key > array, right part of array should be searched. Best way is to
implement a binary search algorithm.
In this case array should be used because the elements of an array will be
stored in consecutive memory locations whereas in the linked list the elements can be
stored in any location and each node has to hold the address of the next element.
A linked list is a set of nodes where each node has two fields „data‟ and a „link‟.
Where „data‟ filed stores the actual piece of information and „link‟ field is used to point
to next node. Basically link filed is nothing but the address node.
Linked list is a kind of series of data structures, which are not necessarily adjacent
in memory. Each structure contains the element and a pointer to a record containing its
successor.
Example:
Types:
20
7. Define singly circular linked list.
In the singly circular linked list only one link is used to point to next element. The
last node‟s link filed points to the first or head node.
In circular doubly linked list the previous pointer of first node and the next pointer
of last nodes are pointed to head node. Head node is a special node which may have any
dummy data or it may have some useful information. Such as total number of nodes in
the list which may be used to simplify the algorithms carrying various operations on the
list.
The main fields of polynomial are coefficient and exponent, in linked list it will
have one more filed called „link‟ field to point to next term in the polynomial. If there are
„n‟ terms in the polynomial then „'n‟ such nodes have to be created.
Nodes of polynomial:
Example:
20. What are the advantages of linked list implementation of list? List the limitation in array
based implementation of list ADT.
Linked list facilities dynamic memory management by allowing elements to be
added or deleted at any time during program execution.
It ensures the efficient utilization of memory space as only that much amount of
memory space is reserved as is required for storing the list of elements.
It is easy to insert or delete elements in a linked list, unlike arrays, which require
shuffling of other elements with each insert and delete operation.
Insertion and deletion operation are expensive as it requires more data movement.
Find and print list operation takes constant time.
Even if the array is dynamically allocated, an estimate of the maximum size of the
list is required which considerably wastes the memory space.
PROGRAMMING
LABORATORY
ORIENTED
OBJECT
UNIT - 4
UNIT - 4
1. Write an algorithm to perform insertion and deletion on a doubly linked list. Give the
relevant coding in C.
2. Consider an array A [1, 2….n]. Given a position, write an algorithm to insert an element
in the array. If the position is empty, the element is inserted easily. If the position is
already occupied, the element should be inserted with minimum number of shifts. (Note:
The elements can be shifted to left or right to make minimum number of moves).
3. Explain the following:
a. Application of lists. (8)
b. Polynomial manipulation (8)
4. Define singly linked list. Write the routine for its operations.
5. Define doubly linked list. Write the routine for its operations.
6. Define circular linked list. Write the routine for its operations.
7. Define circularly doubly linked list. Write the routine for its operations.
UNIT - 2
PART – A
In the double ended queue we can make use of both the ends for insertion of the
elements as well as we can use both the ends for deletion of the elements. That means it
is possible to insert the elements by rear as well as by front. Similarly it is possible to
delete the elements from front as well as from rear.
Types:
i. Input restricted queue
In this type insertion is allowed at one end and deletion is allowed
at both ends.
ii. Output restricted queue
In this type deletion is allowed at one end and insertion is allowed
at both ends.
2. List the applications of queue.
Job scheduling
Categorizing data
Simulation and modeling
Time sharing systems
Mathematics user queuing theory
Computer networks
In implanting depth first search and breadth first search.
3. Give the applications of stack.
Expression conversion
Expression evaluation
Parsing well formed parenthesis
Reversing a string
Storing function calls
Page visited history in a web browser.
Undo sequence in a text editor.
4. Define stack.
A stack is an ordered list in which all insertions and deletions
are made at one end called the top.
The stack is also called as LIFO i.e. Last In First Out data
structure.
If we have to make stack of elements 10, 20, 30, 40, 50, 60 then
10 will be the bottom most element and 60 will be the top most element
in the stack.
5. Define stack full and stack empty.
Stack full
Stfull ( ) – This condition indicates whether the stack is full or not. if the stack is
full then we cannot insert the elements in the stack. Before performing push we must
check stfull ( ) condition.
int stfull ( )
{
if (st.top?=size-1)
return 1;
else
return 0;
}
Thus stfull is a Boolean function. If stack is full it returns 1 otherwise it returns 0.
Stack empty
This condition indicates whether the stack is empty or not. if the stack is empty
then we cannot pop or remove an y element from the stack.
Before popping the elements from the stack we should check stempty() condition.
int stempty ( )
{
if (st.top==-1)
return 1;
else
return 0;
}
6. List the operations of stack.
a. Push
By this operation one can push elements onto the stack. Before performing
push we must check stfull ( ) condition.
void push(int item)
{
st.top++;
st.s[st.top]=item;
}
b. Pop
By this operation one can remove the elements from stack. Before popping
the elements from the stack we should check stempty ( ) condition.
void pop ( )
{
int item;
item = st.s[st.top];
st.top -- ;
return(item);
}
7. Define expression. Give its types.
Example: A+ B
Postfix expression
In this type of expression the arrangement of operands and operator is as
follows.
postfix expression = operand 1 operand 2 operator
Example: AB+
Prefix expression
In this type of expression the arrangement of operands and operator is as
follows.
prefix expression = operator operand 1 operand 2
Example: +AB
9. Define queue. Give example.
The queue can be formally defined as ordered collection of elements that has two
ends named as front and rear. From the front end one can deleted the elements and from
rear end one can insert the elements.
The queue is also called as FIFO i.e. a First In First Out data structure.
Example:
A queue of people who can wait for a city bus at the bus stop. Any new person is
joining at one end of the queue, you can call it as the rear end. When the bus arrives the
person at the other end first enters in the bus, you can call it as the front end.
Representation of queue:
struct queue
{
int que[size], front, rear;
} Q;
10. List the operation on queue.
Queue overflow
Insertion
Queue underflow
Deletion
Display
11. Define queue overflow and queue underflow.
Queue overflow:
The condition resulting from trying to add an element on to a full queue.
Queue underflow:
The condition resulting from trying to remove an element from an empty queue.
12. Write about push and pop operation on queues.
Push:
The insertion of the element in the queue is done by the end called rear. Before
the insertion of the element in the queue it is checked whether or not the queue is full.
Pop:
The deletion of the element from the queue is done by the end called front. Before
performing the delete operation it is checked whether the queue is empty or not.
The formula which has to be applied for setting the front and rear pointers:
Advantages
The main advantage of circular queue is we can utilize the space of the queue
fully.
14. What are the rules of towers of Honai?
Only one disk could be moved at a time.
No longer could disk over reside on a pillar on top of a smaller disk.
A 3rd pillar could be used as an intermediate to store one or more disks, while they
were being moved from source to destination.
15. What is priority queue?
It is a type of queue in which each element is assigned certain priority such that
the order of deletion of elements is decided by their associated priorities.
16. What are the postfix and prefix forms of the expression? A+B*(C-D)/(P-R)
POSTFIF FORM : ABCD-*PR-/+
PREFIX FORM : +A/*B-CD-PR
17. What are the types of queues?
Simple queues.
Circular queue.
Double ended queue.
Priority queue.
18. Mention the advantages of representing stacks using linked list than array.
It is easier to store data of different sizes in a linked list. An array assumes every
element is exactly the same size.
It is easier for a linked list to grow organically. An array‟s size needs to be known
ahead of time, or re-created when it needs to grow.
Shuffling a linked list is just a matter of changing what points to what. Shuffling
an array is more complicated and/or takes more memory.
As long as your iterations all happen in a “foreach” context, you don‟t lose any
performance in iteration.
Adding a new element somewhere in the middle, anywhere the item can be
inserted.
In linked list implementation of list memory are not fixed and it can be allocated
by dynamic memory allocation scheme during the runtime of the program. So
there is no wastage of memory.
19. What is the data structure used to perform recursion? How?
Stack. Because of its LIFO property it remembers its „caller‟ so knows whom to
return when the function has to return. Recursion makes use of system stack for storing
the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function.
Even when such equivalent iterative procedures are written, explicit stack is to be used.
20. What do you understand by polish notation? Explain.
This is also called as prefix notation. In this type of notation the operator followed
by two operands. For example if (a+b)*c is a given expression then its polish notation
will be *+abc.
UNIT –- 5B
PART
PART – A
Extendible hashing is a technique which handles a large amount of data. The data
to be placed in the hash table is by extracting certain number of bits.
In extendible hashing referring the size of directory the elements are to be placed
in buckets. The levels are indicated in parenthesis.
Example:
Types:
1. Internal sorting
2. External sorting
Sorting:
Sorting is a technique for arranging data in particular order. Order means the
arrangement of data. The sorting order can be ascending or descending. The ascending
order means arranging the data in increasing order where as descending order means
arranging the data in decreasing order.
Searching:
Searching is the technique for finding particular element from the set.
Types:
a. Linear Search
b. Binary Search
Merge sort on an input array with „n‟ elements consists of three steps:
Divide: Partition array into two sub lists s1 and s2 with n/2 elements each.
Conquer: Then sort sub list s1 and sub list s2.
Combine: Merge s1 and s2 into a unique sorted group.
10. Define insertion sort. Give its advantages.
Successive element in the array to be sorted and inserted into its proper place with
respect to the other already sorted element.
We start with the second element and put it in its correct place, so that the first
and second elements of the array are in order.
Advantages:
Simple to implement
This method is efficient when we want to sort small number of elements and this
method has excellent performance on almost sorted list of elements.
More efficient than most other simple O (n2) algorithms such as selection sort or
bubble sort.
This is a stable.
It is called in-place sorting algorithm. The in-place sorting algorithm is an
algorithm in which the input is overwritten by output and to execute the sorting
method it does not require any more additional space.
11. Define selection sort.
Scan the array to find its smallest element and swap it with the first element.
Then, starting with the second element scan the entire list to find the smallest element and
swap it with the second element. Then starting from the third element the entire list is
scanned in order to find the next smallest element. Continuing in this fashion we can sort
the entire list.
12. Define shell sort.
In this method the elements at fixed distance are compared. The distance will then
be decremented by some fixed amount and again the comparison will be made. Finally,
individual elements will be compared.
It uses an increment sequence. The increment size is reduced after each pass until
increment size is 1.
13. Define quick sort. Give its advantages.
In this method, the array is split into two sub arrays. This splitting of the array is
based on pivot element. All the elements that are less than pivot should be in the left sub-
array and all the elements that are greater than the pivot should be in the right sub-array.
Advantages:
It reduces unnecessary swaps and moves an item to a greater distance, in one
move.
14. Define radix sort. Give its algorithm.
In radix sort the elements by processing its individual digits. It processes the
digits either by least significant digit (LSD) method or by most significant digit (MSD)
method.
Radix sort is a clever and intuitive little sorting algorithm; radix sort puts the
elements in order by comparing the digits of the numbers.
15. Explain why binary search cannot be performed using linked list.
In binary search algorithm, the mid element needs to be searched. If binary search
is implemented using arrays then by simply saying a[mid] we can access the middle
element of an array in constant time. But for finding the mid element of a linked list we
have to execute separate algorithm and it cannot be done in constant time. Thus
implementing binary search using linked list is very inefficient way. Hence it is not
preferred to implement a binary search using linked list.
16. Define hash table.
Hash table is a data structure used for storing and retrieving data very quickly.
Insertion of data in the hash table is based on the key value. Hence every entry in the
hash table is associated with some key. For example for storing an employee record in the
hash table the employee ID will work as a key.
Using the hash key the required piece of data can be searched in the hash table by
few or more key comparisons. The searching time is then dependent upon the size of the
hash table.
The effective representation of dictionary can be done using hash table. We can
place the dictionary entries in the hash table using hash function.
17. What is hashing? List its techniques.
Hashing is a technique of storing the elements directly at the specific location in
the hash table. The hashing makes use of hash function to place the record at its position.
Using the same hash function the data can be retrieved directly from the hash table.
Techniques
Division method
Mid square method
Multiplicative hash function.
Digit folding
Digit analysis.
18. What is rehashing? Give its advantages.
Rehashing is a technique in which the table is resized. That means the size of the
table is doubled by creating a new table. The total size of the table is usually a prime
number. Following are the situations in which the rehashing is required-
When table is completely full.
With quadratic probing the table is filled half.
When insertions fail due to overflow.
Advantages:
This technique provides the programmer a flexibility to enlarge the tale size if
required.
Only the space gets doubled with simple hash function which avoids occurrence
of collisions.
19. What is collision in hashing?
The situation in which the hash function returns the same hash key for more than
one record is called collision.
20. What is overflow in hashing?
The situation in which there is no room for a new pair in the hash table is called
overflow.
PART - B
LINEAR STRUCTURES
• To identify and create useful mathematical entities and operations to determine what
classes of problems can be solved by using these entities and operations.
• To determine the representation of these abstract entities and to implement the
abstract operations on these concrete representation.
• To understand the relationship of one data elements with the other and organize it
within the memory.
• A data structures helps to analyze the data, store it and organize it in a logical or
mathematical manner.
A data structure is a way of organizing data that considers not only the items stored but also
their relationship to each other.
1. Declaration of data
2. Declaration of operations.
Advantages:
changes easier.
Eg., int,char,float
1. Traversing
2. Searching
3. Inserting
4. Deleting
A singly linked list is a collection of nodes each node is a structure it consisting of an element
and a pointer to a structure containing its successor, which is called a next pointer.
MakeEmpty
IsEmpty
IsLast
Find
Delete
FindPrevious
Insert
Deletelist
Header
First
Advance
Retrieve
10. Write the routine for insertion operation of singly linked list.
Void
Position TmpCell;
TmpCell=malloc(sizeof(struct Node));
if(TmpCell==NULL)
FatalError(“Out of space!!!”);
TmpCell->Element =X;
TmpCell->Next=P->Next;
P->Next=TmpCell;
11. Write the routine for deletion operation of singly linked list.
Void
Delete(ElementType X, List L)
Position P, TmpCell;
P=FindPrevious(X, L);
if (! IsLast(P,L))
TmpCell=P->Next;
P->Next=TmpCell->Next;
Free(TmpCell);
12. List out the advantages and disadvantages of singly linked list.
Advantages:
Disadvantages:
1. Data not present in a linear manner.
Doubly linked list is a collection of nodes where each node is a structure containing the
following fields
Circularly linked list is a collection of nodes , where each node is a structure containing the
element and a pointer to a structure containing its successor.
The pointer field of the last node points to the address of the first node. Thus the linked list
becomes circular.
15. Write the difference between Singly and doubly linked list.
Singly Doubly
node is having one data field node is having one data field
Node takes less memory in SLL. Link Hence, node takes memory in DLL.
16. Write the difference between doubly and circularly linked list.
Doubly Circularly
If the pointer to next node is Null, There is no first and last node.
Last node’s next field is always Last nodes next field points to
Every node has three fields one is it can be a singly linked list
17. Write the difference between cursor and pointer implementation of singly linked list.
Global array is maintained for storing The data are stored in a collection
index value for each data item represents data and a pointer to the next structure.
its address.
in the form of a array from which cells the systems global memory by a call to
can be allocated and also cells can be a malloc() and released by a call to
A stack is a list with a restriction that insertions and deletions can be performed in only one
position namely the end of the list called the top.
19. State the operations on stack. Define them and give the diagrammatic representation.
Push
Pop
Top
Top: top operation examines the element at the top of the stack and returns its
value.
Pop(S) Push(X,S)
Stack S
Top(S)
20. Write the routine for push and pop of linked list.
Void
Push(ElementType X,Stack S)
{
PtrToNode TmpCell;
TmpCell=malloc(sizeof(struct Node));
If(TmpCell==NULL)
FatalError(“out of space!!!”);
else
TmpCell->Element=x;
TmpCell->Next=s->Next;
S->Next=TmpCell;
Void
Pop(stack S)
PtrToNode FirstCell;
If(IsEmpty(S))
Error(“Empty stack”);
Else
FirstCell=S->Next;
S->Next=S->Next->Next;
free(firstCell);
1. Balancing parentheses.
2. Postfix Expression.
3. Function calls.
4. If it is a closing symbol
Then
Report an error
Then
Report an error
Then
Report an error
25. Give the Features of balancing symbols.
1. It is clearly linear.
(j*k)+(x+y)
Ans:jk* xy++
(a+b*c)/d
Ans:
Post fix:
abc*+d/
Evaluation:
2 4 6 * +2/
=13
1. When a function is called the register values and return address are saved.
2. After a function has been executed the register values are resumed on returning
3. The stack is used for resuming the register values and for returning to the
calling statement.
4. The stack overflow leads to fatal error causing loss of program and data.
5. Recursive call at the last line of the program is called tail recursion and also
leads to error.
Queue is a list in which insertion is done at one end called the rear and deletion is performed
at another called front.
Two operations
2. Dequeue-delets and returns the element at the start of the list called as the front.
31. What are the prerequisites for implementing the queue ADT using array?
For each queue data structure the following prerequisites must be satisfied
2. The positions front and rear represents the ends of the queue.
3. The number of elements that are actually in the queue is kept trasck of using
‘size’.
32. How the enqueue and dequeue operations are performed in queue.
To enqueue an element X:
set queue[rear]=x
To dequeue an element
set the return value to queue[front].
Decrement size
Increment front
Void
If(IsFull(Q))
Error(“Full queue”);
Else
Q->Size++;
Q->Rear=Succ(Q->Rear,Q);
Q->Array[Q->Rear]=X;
Void Dequeue(Queue Q)
If(IsEmpty(Q))
Error(“Empty Queue”);
Else
Q->front++;
• Graph Algorithm
• Priority Algorithm
• Job scheduling
• Categorizing Data
36. Define priority queue with diagram and give the operations.
Priority queue is a data structure that allows at least the following two operations.
DeleteMin(H) Insert(H)
Priority Queue H
Operations:
Insert
DeleteMin
1. External sorting.
4. Operating systems.
UNIT II
TREE STRUCTURES
root
T1 T2 T3 …………… TKK
For any node ni the depth of ni is the length of the unique path from the root to ni
eg:
b c d
e f
The depth of e is 2.
B C
D E F G
H
path.
A path from a node n1 to nk is defined as the sequence of nodes n1, n2…..nk such that ni is the
parent of ni+1 for 1≤i<k.
B C
D E F G
H
Eg:
The path from A-H is A-B-D-H
The height of node ni the length of the longest path from ni to a leaf
Eg:
B C
D E F G
struct TreeNode
ElementType Element;
PtrToNode FirstChild;
PtrToNode NextSibling;
};
A Binary tree is a tree in which no node can have more than two children.
A binary tree is a tree in which no node can have more than two children.
B C
D E F G
1. Searching.
2. Compiler design.
16. Draw the expression tree for the given postfix expression using stack.
AB*C+
1 2
*
A B
A B
3
4
* C +
A B
* C
A B
A binary search tree is a tree in which for every node X, the values of all the keys in its left
sub tree are smaller than the key value in X and the values of all the keys in its right sub tree are larger
than the key value in X.
6
4 8
3 5 7 9
2. If the node has one child the node can be deleted after its parent adjusts a
3. If the node has two children the general strategy is to replace the data of this
node with the smallest data of the right sub tree and recursively delete the node
which is empty.
20. What is the average depth of all nodes in an equally likely tree?
The average depth of all nodes in an equally likely tree is O (log N).
1. Deletions in a binary search tree leads to trees which are not equally likely.
3. The average depth is not O (log N) in trees which are not equally likely.
Traveling through all the nodes of the tree in such a way that each node is visited exactly
once.
23. List out the types of Tree traversal?
1. Preorder traversal
2. Inorder traversal
3. Postorder traversal
24. Write the steps and routine for the postorder traversal.
Steps:
Routine:
if(temp!=NULL)
postorder(temp->left);
postorder(temp->right);
printf(“%d”,temp->data);
25. Write the steps and routine for the preorder traversal.
Steps:
Routine:
{
if(temp!=NULL)
printf(“%d”,temp->data);
preorder(temp->left);
preorder(temp->right);
26. Write the steps and routine for the inorder traversal.
Steps:
Routine:
if (temp!=NULL)
inorder(temp->left);
printf(“%d”,temp->data);
inorder(temp->right);
}
27. Perform preorder traversal for the given tree.
B C
D E F G
ABDHECFG
B C
D E
FDBEAC
29. Perform postorder traversal for the given tree.
B C
D E
FDEBCA
i) Leaf
Nodes at the bottommost level of the tree are called leaf nodes
ii) Sibling
BALANCED TREE
Example:
B C
D E F
The balance factor of a node in binary tree is defined to be hR- hL where hL and hR are heights
of left and right subtrees of T. For any node in AVL tree the balance factor should be 1,0 or -1.
3. Give the balance factor of each node for the following tree.
BF=-1
A
B C
BF=1 BF=-1
D E F
BF=0 BF=0
BF=-1
H
BF=0
After insertion of any node in an AVL tree if the balance factor of any node becomes other
than -1,0, or 1 then it is said that AVL property is violated. So the node on the path from the
inserted node to the root needs to be readjusted. Check the balance factor for each node in the
path from inserted node to the root node and adjust the affected subtree such that the entire
subtree should satisfy the AVL property.
• Single Rotation
• Left-Left Rotation
• Right-Right Rotation
• Double Rotation
• Left-Right Rotation
• Right-Left Rotation
A binary heap is a heap data structure created using a binary tree. It can be seen as a binary
tree with two additional constraints:
• The shape property: the tree is an almost complete binary tree; that is, all levels of the tree,
except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not
complete, the nodes of that level are filled from left to right.
• The heap property: each node is greater than or equal to each of its children according to
some comparison predicate which is fixed for the entire data structure.
Selection Algorithm
Graph Algorithm
UNIT –IV
1. Define hashing.
It is the implementation of hash tables. Hashing is a technique used for performing insertions,
deletions and finds in constant average time.
0 50
4 49
• Definition: • Definition:
• It amounts to trying • It is a collision
cells sequentially with resolution method that
wraparound in search eliminates the primary
of an empty cell. clustering problem of
linear probing.
• Function: • Function:
• It is linear ( i.e.)F(i)=i • It is quadratic (i.e.)
F(i)=i2
• Advantages: • Advantages:
• 1.Does not use pointers • 1.Does not use pointers
• No second data • No second data
structure structure
• 3. Time is not required • Time is not required
for allocating new for allocating new
cells. cells.
• If the table is half
empty and the table
size is prime then
inserting a new
element is successful
and guaranteed.
• No primary clustering.
• Disadvantages: • Disadvantages:
• Time for inserting is • There is no guarantee
quite large. of finding an empty
• Primary clustering. cell if the table gets
• Linear probing is a bad more than half full or if
idea if the table is more the table size is not
than half full. prime.
• 4. Bigger table is • Bigger table is needed
needed than separate than separate chaining.
chaining. • The number of
alternative locations is
severely reduced if the
table size is not prime.
• 4. Standard deletion
cannot be performed.
(i.e) a second hash function is applied to X and probing is done at a distance hash2(X),
2hash2(x)………. and so on.
i. Disjoint-set data structures model the partitioning of a set, for example to keep track of the
connected components of an undirected graph. This model can then be used to determine whether two
vertices belong to the same component, or whether adding an edge between them would result in a
cycle.
ii. This data structure is used by the Boost Graph Library to implement its Incremental
Connected Components functionality. It is also used for implementing Kruskal's algorithm to find the
minimum spanning tree of a graph.
A disjoint-set data structure is a data structure that keeps track of such a partitioning. A
union-find algorithm is an algorithm that performs two useful operations on such a data
structure:
• Find: Determine which set a particular element is in. Also useful for determining if two
elements are in the same set.
• Union: Combine or merge two sets into a single set.
UNIT V
GRAPHS
1. Define Graph.
A Graph is defined as G = (V, E) where V is the set of vertices (nodes) and E is the
set of edges(arcs) connecting the vertices. An edge is represented as a pair of vertices (u,v).
2 V = {1, 2, 3, 4, 5}
4 5
A Directed graph is a graph in which the edges are directed. It is also called Digraph.
V={1,2,3,4}
E={(1,2),(2,3),(2,4)
2 3
(3,1),(3,4),(4,3)}
V={1,2,3,4}
E={(1,2),(2,1),(2,3),(3,2)
2 3
2,4),(4,2),(3,4),(4,3),(3,1),(1,3)}
Every edge has an edge in the reverse direction i.e for every edge (U,V) there is an
edge (V,U). Such type of graph is called Symmetric Digraph.
3
V={1,2,3,4}
E={(1,2),(2,1),(2,3),(3,2)
2 3
(2,4),(4,2),(3,4),(4,3),(3,1),(1,3)}
18
1
10 15 V={1,2,3,4,5}
E={(1,2),(1,3),(1,4),(2,3)
2 3
20 (2,4),(2,5),(3,5)}
50
17 25
4 5
3
Vertices 1&2, 2&3, 2&4, 3&4 are
adjacent vertices.
2 3
4
6. Define path.
A Path between vertices (u,v) is a sequence of edges which connects vertices u & v.
2 3
2 3
A Cycle in a graph is a path that starts and ends at the same vertex. i.e path in which
the first and last vertices are same.
1
Ex: {(3, 1), (1, 2),(2,4),(4,3)} is a
Cycle.
2 3
2 3
All vertices are distinct, except that the first and last may or may not be the same.
2 3
2 3
2 3
2 3
15. Define complete graph.
2 3
The adjacency matrix M of a graph G = (V, E) is a matrix of order Vi xVj and the
elements of the unweighted graph M are defined as
= 0 Otherwise
M [i] [j] = Wij, if (Vi, Vj) ∈ E and Wij is the weight of edge (Vi, Vj)
= 0 Otherwise
Example:
1 2 3 4
1 2
1 0 1 1 1
2 0 0 0 1
3 4
3 0 0 0 1
4 0 1 0 0
1 2
3 3
1 2 3
1 2
3 4
Indegree for the vertex 1 is 0, vertex 2 is 2, vertex 3 is 1, and vertex 4 is 2
Ordering of vertices is not possible if the graph is a cyclic graph. Because if there are
two vertices v and w on the cycle, v proceeds w and w proceeds v, so ordering not unique.
The running time of the algorithm for topological sort is O( V 2).For the algorithm
using Queue, the running time is O ( E + V ) if adjacency list are used.
24. State the shortest path problem OR Single source shortest path problem.
N-1
The cost of the path V1,V2….VN is Σ Ci, i+1. . This is referred to as the weighted path
length. i=1
Negative edge means a graph having atleast one edge with a negative weight.
1
3 -10
2 3
A graph having the shortest path with negative weight is known Negative cost cycle.
30. What is the running time for the weighted and unweighted shortest path?
There is no calculation with weights. Only the number of edges on the shortest path is
found.
1. Airport system
2. Street traffic
36. What is a cyclic graph?
2 3
An undirected graph is connected is connected if there is a path frog every vertex to every other
vertex.
2 3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
UNIT I
2 Marks Questions
1. Explain the array implementation of list ADT with routine and example. (16)
2. What is a Linked List? Explain with suitable routine segments for any four
Operations (16)
3. Explain the application of Linked list in detail. (16)
4. Explain Polynomial manipulation using Linked Lists with an example.(16)
5. Explain the different types of Linked Lists and its Implementation.(16)
6. Explain Doubly Linked List with an example.(16)
7. a. With a pseudo code explain how a node can be inserted at a user specified
position in a Doubly Linked List (8)
b. Sort the Following Elements Using Radix Sort. (8)
10, 8, 21, 125, 54,174,187,250,1,65
8. Write a routine to merge two arrays and traverse the array (16)
9. Explain the insertion and deletion operations in a circular single linked list with a
routine and an example. (16)
10. Explain the insertion and deletion operations in a circular double linked list with
routine and an example. (16)
UNIT II
2 Marks Questions
1. Define a stack
2. List out the basic operations that can be performed on a stack
3. State the different ways of representing expressions
4. State the advantages of using infix notations.
5. State the advantages of using postfix notations.
6. State the rules to be followed during infix to postfix conversions
7. State the rules to be followed during infix to prefix conversions.
8. State the difference between stacks and linked lists
9. List the applications of stack
10. Write a routine to check whether the stack is full or empty.
11. Mention the advantages of representing stacks using linked lists than arrays
12. Write the equivalent prefix notation for infix expression p/q*r+s.
13. Define a queue
14. What are the types of queues?
15. Define circular queue
16. Define a priority queue
17. State the difference between queues and linked lists
18. Define a Deque
19. List the applications of queues
20. Write a routine to display the contents of queue.
16/10/8 Marks Questions
1. Explain the operations and the implementation of Stack ADT using Array. (16)
2. Explain the different operation that can be performed on Stacks? Write the algorithm for
each operation. (16)
3. Explain the various application of stack? (Balanced parenthesis, Conversion, Evaluation,
Recursion, etc). (16)
4. Explain the operations and the implementation of Stack ADT using Linked list. (16)
5. Convert the infix expression a+b^c+(d*e/f)*g to postfix expression and evaluate the same
using stack. a=3, b=5, c=2, d=7, e=4, f=1, g=8 (16)
6. What is a queue? Write an algorithm to implement queue with example. (16)
7. Explain the operations and the implementation of Queue ADT using Array (16)
8. Explain the different types of queue. (16)
9. Explain the operations and the implementation of Queue ADT using Linked list. (16)
10. Explain Prefix, Infix and postfix expressions with an example.
UNIT 1&2
1. Define ADT.
2. What are the advantages of Linked List over arrays?
3. What are the advantages of doubly Linked List over singly linked list?
4. List the applications of List ADT.
5. List the applications of Stack and Queue.
6. What is Deque?
7. Convert the infix expression (a+b*c-d)/(e*f-g)
8. What is circular queue?
9. Write a routine to return the top element of stack.
10. What is the working principle of Radix sort?
11. What is priority Queue?
PART B
1. Explain the array and linked list implementation of Stack.
2. Explain the array and linked list implementation of Queue.
3. What are the various linked list operations? Explain
4. Write routines to implement addition, subtraction & differentiation of two
polynomials.
5. Explain how stack is applied for evaluating an arithmetic expression.
6. Explain cursor implementation of list.
Unit 3
PART A
1. Compare General tree with binary tree.
2. Define the following terminologies.
Sibling,Parent,Depth,height,Level,leaf,Degree.
3. What is Full and Complete binary tree?
4. Define binary search tree.
5. Give the array and linked list representation of tree with example.
6. Define tree traversal.
7. Give the preorder, inorder and post order traversal for the following graph.
8. Draw the binary search tree for the following inputs. 70,15,29,33,44,12,79
9. Differentiate binary tree and binary search tree.
10. What is threaded binary tree?
11. Show the maximum number of nodes in an binary tree of height H is 2H+1-1
12. List the steps involved in deleting a node from a binary search tree.
13. A full node is a node with two children. Prove that the number of full nodes plus one
is equal to the number of leaves in a non empty binary tree.
14. List the applications of tree.
PART B
1. Write an algorithm to find an element from binary search tree.
2. Write an algorithm to insert , delete, Find minimum and maximum element from a
binary search tree.
3. What are the tree traversal techniques? Explain with an example.
4. Explain the operations performed on threaded binary tree in detail.
Unit 4
PART A
1. Define AVL tree.
2. What is binary heap?
3. What are the 2 properties of a binary heap?
4. Define B-tree.
5. What is percolating Up and percolating down?
6. What do you mean by self adjusting tree?
7. What is splay tree?
8. What is a balance factor?
9. List the applications of Binary Heap.
10. Difference between B tree and B+ tree.
11. List the different ways of implementing priority queue.
12. What is Min heap and Max heap?
PART B
1. Explain the AVL rotations.
2. Construct splay tree for the following values.
1,2,3,4,5,6,7,8,9
3. Explain the Basic operations performed in a Binary heap.
4. Construct a Min and MAX heap for the following values.
23,67,1,45,7,89,56,35
5. Write a routine to perform insertion in a B-tree
Unit 5
PART A
6. Define hashing.
7. What is collision? What are the different collision resolving techniques?
8. What is open addressing?
9. What is extendible hashing?
10. Write a routine to perform the hash function.
11. What is hash table?
12. Define a graph.
13. Define path,degree,cycle,loop,directed graph, undirected graph,bigraph, weighted graph.
14. Define topological sort.
15. Define minimum spanning tree.
16. Write the routine for Depth first and breadth first traversal.
17. List the graph traversal techniques.
18. List the applications of depth first traversal.
19. List the applications of graph.
20. What is an adjacency matrix? What are the different ways for implementing it?
21. Compare directed and undirected graph.
PART B
1. Define Hash function. Write routines to find and insert an element in separate
chaining.
2. Explain extendible hashing to resolve collision.
3. Explain open addressing with example.
4. Write a note on Dynamic equivalence problem.
5. Write short notes on Smart Union algorithm.
B.E./B.Tech. DEGREE EXAMINATION, NOVEMBER/DECEMBER 2016.
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
PART B — (5 x 16 80 marks)
11. (a) Explain functions with variable number of arguments in detail. Write a
C program to find the sum of a numbers using functions with variable number of
arguments. (16)
Or
(b) Explain the following:
(i) Function pointer in C (8)
(ii) Control Statements in C. (8)
12. (a) (i) What is a structure? Write a C program to add and subtract the two
complex numbers using structures. (8)
(ii) Explain the concept of random access files with an example. (8)
Or
Page 1 of 22
(b) Store ten names of students in a file called ‗data .txt‘. Perform operations to sort their names
alphabetically. Write the sorted names into another file called ‗names .txt‘. Display the names
from ‗names .txt‘ by opening the file in read mode. Close the files after performing all
operations. (16)
13. (a) What is singly linked list? Write a C program that uses functions to perform the following
operation on singly list with suitable diagrammatic representations. Consider all cases:
(i) Insertion (ii) Deletion (iii) Traversal in both ways. (16)
Or
(b) Illustrate the necessary algorithms to implement doubly linked list and
perform all the operations on the created list. (16)
14. (a) Develop an algorithm to implement Stack ADT. Give relevant examples
with diagrammatic representations. (16)
Or
(b) (i) Write an algorithm to implement circular queue using arrays. (10)
(ii) Show the simulation using stack for converting the expression
p*q+(r-s/t) from infix to prefix. (6)
15. (a) (î) Sort the given integers and show the intermediate results using
selection sort. 45, 25, 10, 2, 9, 85, 102, 1. (8)
(ii) Write a C code to sort an integer array using selection sort. (8)
Or
(b) What is hashing? Explain open addressing and separate chaining
methods of collision resolution techniques with examples. (16)
Page 2 of 22
B.E./B.Tech. DEGREE EXAMINATION, MAY/JUNE 2016.
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
12. (a) (i) Write a C program to read the contents of a file ―input.txt‖ and write the
(ii) Explain in detail about random access file concept with an example (8)
OR
Page 3 of 22
13. (a) Write C code for singly linked list with insert,delete,display operations using
structure pointer (16)
OR
(b) Illustrate the algorithms to implement the doubly linked list and perform all the
(ii) Differentiate between double ended queue and Circular queue. (4)
OR
(b)(i) Write an algorithm to convert the infix expression to postfix expression.(10)
(ii) Show the simulation using stack for the following expression to convert
OR
(b) Sort the following integer elements using Quick Sort 40, 20,70,14,60,61,97,30 (16)
Page 4 of 22
B.E./B.Tech. DEGREE EXAMINATION, DECEMBER 2015/JANUARY 2016
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
Page 5 of 22
12.(a)Define a structure data type named date containing three integer members day, month and
year. Develop an interactive modular program to perform the following tasks :
(i) To read data into structure members by a function. (8)
(ii) To print the date in the following format : April 15, 2015 by a
second function. (8)
(OR)
(b)Write a C program to create a file that could store details about five products. Details include
product code, product names cost and number of items available which are provided through
keyboard. Get the input as product code and display the details of the product from the file.(16)
13 (a) Illustrate the algorithms to create the singly linked list and perform all the operations on
the created list. (16)
(OR)
(b) Write a program to add two polynomials using linked list. (16)
14. (a) (i) Write an algorithm to convert the infix expression to postfix expression. (10)
(ii) Show the simulation using stack for the following expression:
12 +3 *14-(5* 16) + 7 (6)
(OR)
b) (i) Write an algorithm to implement the circular queue using arrays. (10)
(ii) List the applications of queues. (6)
15. (a) (i) Sort the following sequence using quick sort.
2, 13,45,56,27, 18, 24,30, 87,9 (8)
(ii) Write an algorithm to search a number in a given set of numbers using binary search (8)
(OR)
(b) Explain the open addressing and chaining methods of collision resolution
techniques in hashing. (16)
Page 6 of 22
B.E./B.Tech. DEGREE EXAMINATION, APRIL/MAY 2015.
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
Answer ALL Questions
PART A-(10 × 2 = 20 marks)
1. Give two examples of C preprocessor with syntax.
2. What are function pointers in C ? Explain with example.
3. What is the difference between getc( ) and getchar( ) ? Explain.
4. Explain the syntax as given below:
Fread(&my_record,sizeof(struct rec),ptr_myfile);
5. Define ADT.
6. What is static linked list ? State any two applications of it.
7. Write the syntax of calloc( ) and realloc( ) and mention its application in linked list.
8. Given the prefix for an expression, write its postfix
- *-+abc/ef–g/hi
9. What is meant by internal and external sorting ? Give four example of each type.
10. State the applications of linear and binary search techniques.
PART B ( 5 × 16 = 80 marks )
11. (a) (i) Write a function that returns a pointer to the maximum value of an array of
double‘s. If the array is empty, return NULL.
Double * maximum(double *a, int size ) ; (8)
(ii) Write a C program to find all the roots of a quadratic equation. (8)
(or)
(b) (i) Write a C program using function to check if the given input number is palindrome
or not. (8)
(ii) Explain the C preprocessor operations, each with a neat example that is used to
create macros. (8)
12. (a) (i) Write a C program that uses functions to perform the following operations using
structure:
1) Reading a complex number
2) Writing a complex number
3) Addition of two complex numbers
4) Multiplication of two complex numbers (12)
(ii) State the advantage and disadvantage of structures and unions in C Programming (4)
(or)
Page 7 of 22
(b) (i) Perform the following to manipulate file handling using C.
1) Define an input file handle called input_file , which is a pointer to a type
FILE.
2) Using input_file, open the file results.dat for read mode.
3) Write C statements which tests to see if input_file has opened the data file
successfully. If not,print and error message and exit the program.
4) Write C code which will read a line of characters (terminated by a \n)from
input_file into a character array called buffer. NULL terminate the nuffer
upon reading a \n.
5) Close the file associated with input_file.
(12)
14. (a) (i) Write C program that checks if experssion is correctly parenthesized using stack.
(12)
(ii) Write the function to checkfor state status as Full ( ) or Empty ( ).
(4)
(or)
(b) Write C program to implement Queue functions using Arrays and Macros.
(16)
15. (a) (i) Sort the given integers and show the intermediate results using shell sort
35 , 12 , 14 , 9 , 15 , 45 , 32 , 95 , 40 , 5 (8)
(ii) Write C code to sort an integer array using shell sort. (8)
(or)
(b) (i) Explain a C code to perform binary search. (10)
(ii) Explain the Rehashing techniques. (6)
Page 8 of 22
B.E./B.Tech. DEGREE EXAMINATION, NOVEMBER/DECEMBER 2014.
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
Answer ALL Questions
PART A-(10 × 2 = 20 marks)
1. Define an array. Give an example.
2. Give example on call by reference.
3. What are the statements used for reading a file.
4. Define the need for union in C.
5. What are abstract data type?
6. What is circular linked list?
7. Give the applications of stack.
8. What is double ended queue?
9. Define extendible hashing.
10. Differentiate internal and external sorting.
PART B – (5 X 16 = 80 marks)
1. (a) Explain the various control statements in C language with example in detail.(16)
Or
(b) Briefly discuss about:
(i) Functions with number of arguments.
(ii) Function Pointers. (8 + 8)
12. (a) Explain the difference between structure and union with examples. (16)
Or
(b) Explain about file manipulations in detail with suitable program. (16)
13 (a) Describe the creation of a doubly linked list and appending the list. Give relevant coding
in C. (16)
Or
(b) Explain the following:
(i) Applications of lists.
(ii) Polynomial manipulation. (8 + 8)
14 (a) Discuss about Stack ADT in detail. Explain any one application of stack. (16)
Or
(b) Explain about Queue ADT in detail. Explain any one application of queue with suitable
example. (16)
Page 9 of 22
15 (a) What are the different types of hashing techniques? Explain them in detail with example.
(8 + 8)
Or
(b) Write an algorithm to sort a set of ‗N‘ numbers using quick sort. Trace the algorithm for
the following set of numbers: 88, 11, 22, 44, 66, 99, 32, 67, 54, 10. (16)
Page 10 of 22
B.E./B.Tech. DEGREE EXAMINATION,MAY/JUNE 2014.
Second Semester
Computer Science and Engineering
CS 6202 – PROGRAMMING AND DATA STRUCTURES – I
(Common to Computer and Communication Engineering and Information Technology)
(Regulation 2013)
Time : Three hours Maximum : 100 marks
Answer ALL Questions
PART A - (10 X 2 = 20 marks)
1. With the help of the printf function show how C handles functions with variable number
of arguments.
2. Define macro with an example.
3. Give applications in which union rather than structures can be used.
4. Will the following declaration work. Justify your answer.
Struct Student
{
int rollno = 12;
float marks[] = { 55, 60, 56 );
char gender;
};
5. Should arrays or linked lists be used for the following types of applications. Justify your
answer.
(a) Many search operations in sorted list
(b) Many search operations in unsorted list
6. What is advantage of an ADT?
7. Define double ended queue.
8. List the applications of a Queue.
9. What is the time complexity of binary search?
10. List sorting algorithm which uses logarithmic time complexity.
Page 11 of 22
PART B – ( 5 X 16 = 80 MARKS)
11 (a) (i) Write a c program to find the unique elements in an array using a function ‗Unique‖.
The function takes the array as a parameter and prints the unique elements . (10)
(ii) Write a C program to print Fibonacci numbers. (6)
Or
(b) Write a C program to multiply two matrices that are represented as pointers. Use a
function pointer to the function ‗Multiply‘ which takes the two matrices as parameter and prints
the result of the multiplication. (16)
12 (a) (i) Write a C program to read the contents of a file ―in.txt‖ from last to first and write the
contents to ―out.txt‖. (8)
(ii) Write the function prototype and explain how files are manipulated in C. (8)
Or
(b) (i) Create a structure to store a complex number and write function (for addition) that
handles this new structure. (8)
(ii) Write a program to perform the following operations for the customers of a bank using
the concept of structures. (8)
(1) Input the customer details like name, account number and balance.
( 2) When a withdrawal transaction is made the balance must change to reflect it.
( 3) When a deposit transaction is made the balance must change to reflect it..
13 (a) Write an algorithm to perform insertion and deletion on a doubly linked list. (16)
Or
(b) Consider an array A[1:n]. Given a position, write an algorithm to insert an element in the
array. If the position is empty, the element is inserted easily. If the position is already
occupied the element should be inserted with the minimum number of shifts. (Note: The
elements can shift to the left or right to make the minimum number of moves) (16)
14 (a) Write an algorithm to convert an infix expression to a postfix expression. Trace the
algorithm to convert the infix expression ―(a+b)*c/d+e/f‖ to a postfix expression. Explain
the need for infix and postfix expressions. (16)
Or
Page 12 of 22
(b) Write an algorithm to perform the four operations in a double ended queue that is
implemented as an array. (16)
15 (a) Write short notes on hashing and the various collision resolution techniques. (16)
Page 13 of 22
B.E./B.Tech. DEGREE EXAMINATION, NOVEMBER/DECEMBER 2009
Third Semester
Information Technology
IT 2201 — DATA STRUCTURES AND ALGORITHMS
(Regulation 2008)
Time : Three hours Maximum : 100 Marks
Answer ALL Questions
PART B — (5 × 16 = 80 Marks)
11. (a) (i) Write the insertion and deletion procedures for cursor based linked
lists. (8)
(ii) Write the algorithm for the deletion and reverse operations on
doubly linked list. (8)
Or
(b) (i) Write an algorithm for Push and Pop operations on Stack using
Linked List. (8)
(ii) Explain the addition and deletion operations performed on a
circular queue with necessary algorithms. (8)
12. (a) (i) Write the algorithm for pre-order and post-order traversals of a
binary tree. (8)
(ii) Explain the algorithm to convert a postfix expression into an
expression tree with an example. (8)
Or
(b) (i) Write an algorithm to insert an item into a binary search tree and
trace the algorithm with the items 6, 2, 8, 1, 4, 3, 5. (8)
(ii) Describe the algorithms used to perform single and double rotation
Page 14 of 22
on AVL tree. (8)
13. (a) Discuss the common collision resolution strategies used in closed
hashing
system. (16)
Or
(b) (i) What is union-by-height? Write the algorithm to implement it. (8)
(ii) Explain the path compression with an example. (8)
14. (a) (i) What is topological sort? Write an algorithm to perform topological
sort. (8)
(ii) Write the Dijkstra’s algorithm to find the shortest path. (8)
Or
(b) Write the Kruskal’s algorithm and construct a minimum spanning tree
for the following weighted graph. (16)
15. (a) (i) Formulate an algorithm to multiply n-digit integers using divide
and conquer approach. (8)
(ii) Briefly discuss the applications of greedy algorithm. (8)
Or
(b) Find the optimal tour in the following traveling salesperson problem
using dynamic programming : (16)
Page 15 of 22
B.E./B.Tech. DEGREE EXAMINATION, NOVEMBER/DECEMBER 2010
Third Semester
Information Technology
IT 2201 — DATA STRUCTURES AND ALGORITHMS
(Regulation 2008)
Time : Three hours Maximum : 100 Marks
Answer ALL questions
PART B — (5 × 16 = 80 Marks)
11. (a) (i) Derive an ADT to perform insertion and deletion in a singly linked
list. (8)
(ii) Explain cursor implementation of linked lists. Write the
essential operations. (8)
Or
(b) (i) Write an ADT to implement stack of size N using an array. The
elements in the stack are to be integers. The operations to be
supported are PUSH, POP and DISPLAY. Take into account the
exceptions of stack overflow and stack underflow. (8)
(ii) A circular queue has a size of 5 and has 3 elements 10, 20 and 40
where F = 2 and R = 4. After inserting 50 and 60, what is the value
of F and R. Trying to insert 30 at this stage what happens? Delete
2 elements from the queue and insert 70, 80 & 90. Show the
sequence of steps with necessary diagrams with the value of F & R.
(8)
Page 16 of 22
12. (a) (i) Write an ADT to construct an AVL tree. (8)
(ii) Suppose the following sequences list nodes of a binary tree T in
preorder and inorder, respectively :
Preorder : A, B, D, C, E, G, F, H, J
Inorder : D, B, A, E, G, C, H, F, J
Draw the diagram of the tree. (8)
Or
(b) (i) Write an ADT for performing insert and delete operations in a
Binary Search Tree. (8)
(ii) Describe in detail the binary heaps. Construct a min heap tree for
the following :
5, 2, 6,7, 1, 3, 8, 9, 4 (8)
13. (a) (i) Formulate an ADT to implement separate chaining hashing
scheme. (8)
(ii) Show the result of inserting the keys 2, 3, 5, 7, 11, 13, 15, 6, 4 into
an initially empty extendible hashing data structure with M = 3. (8)
Or
(b) (i) Formulate an ADT to perform for the Union and find operations of
disjoint sets. (8)
(ii) Describe about Union-by-rank and Find with path compression
with code. (8)
14. (a) (i) Write routines to find shortest path using Dijkstra’s algorithm. (8)
(ii) Find all articulation points in the below graph. Show the depth first
spanning tree and the values of DFN and Low for each vertex. (8)
Or
(b) (i) Write the pseudo code to find a minimum spanning tree using
Kruskal’s algorithm. (8)
(ii) Find the topological ordering of the below graph. (8)
15. (a) (i) Discuss the running time of Divide-and-Conquer merge sort
algorithm. (8)
(ii) Explain the concept of greedy algorithm with Huffman codes
example. (8)
Or
(b) Explain the Dynamic Programming with an example. (16)
Page 17 of 22
Page 18 of 22
Page 19 of 22
Page 20 of 22
Page 21 of 22
Page 22 of 22