0% found this document useful (0 votes)
27 views174 pages

DS Notes-1

The document is a comprehensive guide on Data Structures, detailing their definitions, types (primitive and non-primitive), and various operations such as traversing, searching, inserting, deleting, sorting, and merging. It also covers algorithm design approaches (top-down and bottom-up), abstract data types, and specifically discusses stacks, including their implementation in C programming. Additionally, it provides examples of converting decimal to binary and evaluating postfix expressions using stacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views174 pages

DS Notes-1

The document is a comprehensive guide on Data Structures, detailing their definitions, types (primitive and non-primitive), and various operations such as traversing, searching, inserting, deleting, sorting, and merging. It also covers algorithm design approaches (top-down and bottom-up), abstract data types, and specifically discusses stacks, including their implementation in C programming. Additionally, it provides examples of converting decimal to binary and evaluating postfix expressions using stacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 174

1|RKDEMY

RKDEMY
DEGREE / DIPLOMA ENGINEERING

SEM-III

DATA STRUCTURES
Computer & Information Technology

By -: Nitin Sir

THANE NERUL DADAR

1st floor new matruvandana society, near thane railway station behind kopri bus stop, Thane (east).
By Nitin Sir
2|RKDEMY

INTRODUCTION TO DATA STRUCTURE


Q.1 What is Data structure [5M MAY 15]
Data Structures
A data structure is a way of storing and organizing data in such way that we
can perform operation on these data in an efficient way.

Areas in which data structures are applied extensively

• Compiler Design,
• Operating System,
• Database Management System,
• Statistical analysis package,
• Numerical Analysis,
• Graphics,
• Artificial Intelligence,

Q . 2 Explain different types of data structure with example [M-


5 May-18]
Classification Data Structures

By Nitin Sir
3|RKDEMY

Types of Data structure [5M MAY17, DEC17]


Data structure is divided into two types

Primitive & Non-Primitive

1. Primitive: The integers, reals, logical data, character data, pointers


and reference are primitive data structures. these data types are
available in most programming language as build in type.

2. Non-primitive: These data structure is derived from primitive data


structures.
examples of non-primitive data structures: array, structure, union,
linked list, stack, queue, tree, graph.

List data structure is divided into two types [5M DEC-16]


a. Linear data structure:
Elements are arranged in a linear fashion, A linear data structure
traverses the data elements sequentially, in which only one data
element can directly be reached, Linked list stores data in an
organized linear fashion All one-one relation can be handled
through linear data structure.

e.g Stack , Queue

b. Non-Linear data structure:


Element are arranged in nonlinear fashion, In this, the data elements
can be attached to more than one element exhibiting the hierarchical relationship,
all one-many, many-one or many-many relations are handled in
Non-linear data structure.
e.g Trees, Graphs

By Nitin Sir
4|RKDEMY

Q.3 What are various operations on data structure. [M-3 DEC-


18]
Operations on Data Structures

• Traversing :
Traversing a data structure is accessing each data and accessing
only once.

• Searching :
Searching is finding the location of a data in within the given
data structure.

• Inserting :
Inserting is adding a new data in the data structure.

• Deleting :
Deleting is removing a data from the data structure.

• Sorting :
Sorting is arranging of data in some logical order.

• Merging :
Merging is combining of two similar data structures.

Different Approaches for Designing an Algorithm

Design of an algorithm is an important issue. There are several approaches


for designing an algorithm. These approaches include:

1. Top-down approach.
2. Bottom-up approach.

Top-Down Approach

One has to write a program to solve a specific task.

A programmer tries to partition the solution into subtasks. Each subtask is


similarly decomposed until all task are expressed within a programming
language.

By Nitin Sir
5|RKDEMY

Top-down method of design is based on decomposing a large problem into


sub problems and keep repeating this process till the resulting sub-problems
are so simple that their solutions can be expressed in a few lines of a
programming language.

Bottom-Up Approach

This approach is reverse of top-down approach. Here, the different parts of


the problem are first solved using a programming language and then these
pieces of programs are combined into a complete program.

Define ADT (Abstract data type)

• Stack is an order list with insertion and deletion can be performed at


only one position called top.
• A big program is never written as monolithic piece of program, instead
it is broken down in smaller modules and each module is developed
independently.
• Main program uses the services of next level function without knowing
their implementation details. thus level of abstraction is created.
• Abstraction for primitive data type is provided by compiler.
• eg: we use integer data type and also perform various operation on
them without knowing representation and how operations are
performed on them.
• eg: z=x+y; meaning of operation ‘+’ is defined by complier and its
implementation details remain hidden from user.

By Nitin Sir
6|RKDEMY

STACKS
What is stack

• Stack is a LIFO(Last In First Out) structure.


• Stack is a linear list where all insertion and deletion are permitted only
at one end of list.
• Every time an element is added, it goes on the top of the stack, the only
element that can be removed is the element that was at the top of the
stack.

By Nitin Sir
7|RKDEMY

Inserting Data into Stack :-

Removing Data from Stack :-

STACK as an ADT

Stack can be represented using an arraYy, a one-dimensional array can be


used to hold elements of stack.

Another variable “top” is used to keep track of the index of the top most
element.

typedef struct stack


{
int data[SIZE];
int top;
}stack;

By Nitin Sir
8|RKDEMY

void initialize(stack *p):


It initializes an empty stack . Initial value of top is set to -1.

int empty(stack *p):


Functions checks whether the stack is empty, It returns 1 or 0
depending on whether the stack is empty or not.

int full (stack *p):


This function checks whether the stack is full. The function returns 1
or 0 depending on whether the stack is full or not.

int pop (stack *p):


The function deletes topmost element from the stack and also returns
it to the calling program.

void push (stack *p , Int x):


The function inserts the element x onto the stack pointed by P.
Insertion will cause an overflow if the stack is full.

Applications of Stack
• Expression Conversion
a) Infix to postfix c) postfix to infix
b) Infix to prefix d) prefix to infix
• Expression Evaluation
• Parsing
• Simulation of recursion
• Function Call

Implementation of Stack
• Stack can be easily implemented using an Array or a Linked List.
• Arrays are quick, but are limited in size and Linked List requires
overhead to allocate, but is not limited in size.

By Nitin Sir
9|RKDEMY

typedef struct stack


{
int data[max];
int top;
} stack;

a) Initilize stack
void initialize (stack*s)
{
S→ top= -1;
}

b) Determine stack is empty


int empty (stack*s)
{
if (s→top = = -1)
{
return (1);
}
else
{
return (0);
}
}

c) Determine stack is full


int full (stack*s)
{
If (s→top = = max -1)
{

By Nitin Sir
10 | R K D E M Y

return (1);
}
else
{
return (0);
}
}

d) Insert element into stack


void push (stack*s, int x)
{
s→top = s→top + 1;
s→data[s→top] = x;
}

e) Remove element from stack


int pop (stack*s)
{
int x;
x=s→data [s→top];
s→top = s→top – 1;
return(x);
}

By Nitin Sir
11 | R K D E M Y

WRITE A C PROGRAM FOR IMPLEMENTING STACK USING ARRAY.

#include<stdio.h>
#include<conio.h>
#define MAX 6
typedef struct stack
{
int data[MAX];
int top;
}stack;
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *, int );
void print(stack *);
void main( )
{
stack s;
int x, op;
init(&s);
do{
printf(“\n\n1)Push\n2)Pop\n3)Print\n4) Quit”);
printf("\n Enter Your choice : ");
scanf("%d", &op);
switch(op)
{
case 1:print(“\n enter a number:”);
scanf(“%d”,&x);
if(!full(&s))
push(&s,x);
else
printf(“\n Stack is full……”);
break;
case 2:if(!empty (&s))
{
x=pop(&s);
printf(“\n popped value = %d”,x);
}
else
printf(“\nStack is empty……….”);
break;

By Nitin Sir
12 | R K D E M Y

case 3:print(&s);
break;
}
}while( op != 4);
}
void init(stack *s)
{
s->top = -1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
else
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
else
return(0);
}
void push(stack *s,int x)
{
s->top = s->top + 1;
s->data[s->top] = x;
}
int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}
void print(stack *s)
{
int i;
printf(“\n”);
for(i=s->top; i>=0; i--)
{
printf(“%d”,s->data[i]);

By Nitin Sir
13 | R K D E M Y

}
}

Applications of Stack [5M DEC16]


• Expression Conversion
a) Infix to postfix c) postfix to infix
b) Infix to prefix d) prefix to infix
• Expression Evaluation
• Parsing
• Simulation of recursion
• Function Call

By Nitin Sir
14 | R K D E M Y

Convert Decimal to binary

(𝟐𝟏)𝟏𝟎 = ( ? )𝟐

21 % 2 =1
1

10 % 2 =0
0
1

1
5%2=1
0
1

0
2%2=0 1
0
1

1%2=1

1
0
1
0
1

By Nitin Sir
15 | R K D E M Y

WRITE A PROGRAM IN C TO CONVERT DECIMAL TO BINARY USING


STACK.

#include <stdio.h.>
#include<conio.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data [MAX];
int top;
}stack;
void init(stack*);
int empty(stack*);
int full(stack*);
int pop(stack*);
void push(stack*,int);
void main()
{
stack s;
int x;
init(&s);
printf(“Enter a decimal number\n”);
scanf(“%d”, &x);
while((x!=0)
{
if(!full(&s))
{
push(&s, x%2);
x=x/2;
}
else
{
printf(“Stack overflow”);
}
}
while (!empty(&s))
{
x=pop(&s);
printf(“%d”,x);
}
getch();

By Nitin Sir
16 | R K D E M Y

}
void init(stack *s)
{
S→top= -1;
}
int empty (stack *s)
{
if(s→top ==-1)
return(1);
else
return(0);
}
int full(stack *s)
{
if(s→top = = MAX-1)
return(1);
else
return(0);
}
void push(stack *s, intx)
{
s→top=s→top+1;
s→data[s→top]=x;
}
int pop (stack *s)
{
int x;
x= s→data[s→top];
s→top= s→top-1;
return(x);
}

Expression representation

An Expression is a collection of operators and operands that


represents a specific value.
There are three methods for representation of an expression.
• Infix (x+y) Operator between operands
• Prefix +xy Operator before operands
• Postfix xy+ Operator after operands

By Nitin Sir
17 | R K D E M Y

Evaluation of a postfix expression using a stack

Given Expression

6 5 3 + 9* + Initially stack is empty.

First token is an operand , push 6 on the push

5 3+ 9* +
6

Next token is and operand ,push 5 on the stack

3+9*+
5

Next token is operand , push 3 on the stack .

+ 9 * +
3
5

Next token is an operator “+” , pop two operands 3 and 5 ,


add them and push the result on the stack.

9 * +
8
6

Next token is an operand , push 9 on the stack.

* + 9

By Nitin Sir
18 | R K D E M Y

Next token is an operator “ * ”, pop two operands 9 and 8,multiply them


and push the result on the stack.

+
72

Next token is an operator “+” , pop two operands 72 and 6 , add them
and push the result back on the stack.

78

Value of the expression = 78

WRITE A PROGRAM TO EVALUATION A POSTFIX EXPRESSION [10M


MAY 18]

#include <stdio.h.>
#include<conio.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data [MAX];
int top ;
}stack;

void init(stack*);
int empty(stack*);
int full(stack*);
int pop(stack*);
void push(stack*,int);
void main()
{
stack s;
int x;
int op1, op2,val;

By Nitin Sir
19 | R K D E M Y

init(&s);
printf(“Enter the expression\n”);
while((x=getchar())!=’\n’)
{
if(isdigit(x))
{
push(&s, x-48);
}
else
{
Op2=pop(&s);
Op1=pop(&s);
Val=evaluate(x,op1,op2);
Push(&s,val);
}
}
Val=pop(&s);
Printf(“\n value of expression=%d”,val);
getch();
}
int evaluate(char x, int op1, int op2)
{
If(x==’+’)
return(op1+op2);
If(x==’-’)
return(op1-op2);
If(x==’*’)
return(op1*op2);
If(x==’/’)
return(op1/op2);
If(x==’%’)
return(op1%op2);
}
void init(stack *s)
{
S→top= -1;
}

By Nitin Sir
20 | R K D E M Y

int empty (stack *s)


{
if(s→top = =-1)
return(1);
else
return(0);
}
int full(stack *s)
{
If(s→top = = MAX-1)
return(1);
else
return(0);
}
void push(stack *s, int x)
{
s-> top=s ->top+1;
s->data[s->top]=x;
}
int pop (stack *s)
{
int x;
x= s-> data[s->top];
s->top= s->top-1;
return(x);
}

Convert the following expression Q into the postfix form. Q =(A+B)*C-


D/E*(F/G).
Show stack representation.

Sr. no Input Stack Output

1 (A+B)*C-D/E*(F/G) Empty -

2 A+B)*C-D/E*(F/G) ( -
3 +B)*C-D/E*(F/G) ( A

By Nitin Sir
21 | R K D E M Y

4 B)*C-D/E*(F/G) (+ A
5 )*C-D/E*(F/G) (+ AB
6 *C-D/E*(F/G) Empty AB+
7 C-D/E*(F/G) * AB+
8 -D/E*(F/G) * AB+C
9 D/E*(F/G) - AB+C*
10 /E*(F/G) - AB+C*D
11 E*(F/G) -/ AB+C*D
12 *(F/G) -/ AB+C*DE
13 (F/G) -* AB+C*DE/
14 F/G) -*( AB+C*DE/
15 /G) -*( AB+C*DE/F
16 G) -*(/ AB+C*DE/F
17 ) -*(/ AB+C*DE/FG
18 END -* AB+C*DE/FG/
19 END Empty AB+C*DE/FG/*-
Given Expression =(A+B)*C-D/E*(F/G).
Postfix Expression = AB+C*DE/FG/*-

Convert the following expression to postfix form


(f-g)*((a+b)*(c-d))/e [5M May-17]

WRITE A PROGRAM TO CONVERTS AN EXPRESSION FROM INFIX TO


POSTFIX USING STACK.[10M DEC16,DEC17]
#include<stdio.h>
#include<conio.h>
#define MAX 100
typedef struct Stack
{
int data[MAX];
int top;
}stack;
void Infix_To_Postfix(char infix[], char postfix[]);
void init(stack* s);
void push(stack* s, int x);
int top(stack* s );
int precedence(char x);
int empty(stack* s);
int pop(stack* s);
void main()
{
char infix[100], postfix[100];
printf("Enter infix expression\n");
gets(infix);
Infix_To_Postfix(infix, postfix);
printf("Postfix expression is\n");
printf(postfix);

By Nitin Sir
22 | R K D E M Y

_getch();
}
void Infix_To_Postfix(char infix[], char postfix[])
{
stack s;
char token, x;
int i, j = 0;
init(&s);
for (i = 0; infix[i] != '\0'; i++)
{
token = infix[i];
if (isalnum(token))
{
postfix[j++] = token;
}
else if (token == '(')
{
push(&s, token);
}
else if (token == ')')
{
while ((x = pop(&s)) != '(')
{
postfix[j++] = x;
}
}
else
{
while (precedence(token) <= precedence(top(&s)) && !empty(&s))
{
x = pop(&s);
postfix[j++] = x;
}
push(&s, token);
}
}
while (!empty(&s))
{
x = pop(&s);
postfix[j++] = x;
}
postfix[j] = '\0';

}
int precedence(char x)
{
if (x == '(')
return(0);
if (x == '+' || x == '-')
return(1);
if (x == '*' || x == '/')
return(2);
return(3);
}
void init(stack* s)
{
s->top = -1;
}
int empty(stack* s)
{
if (s->top == - 1)
return (1);

By Nitin Sir
23 | R K D E M Y

else
return(0);
}
void push(stack* s, int x)
{
s->top = s->top + 1;
s->data[s->top] = x;
}
int pop(stack* s)
{
int x;
x = s->data[s->top];
s->top = s->top - 1;
return(x);
}
int top(stack* p)
{
return(p->data[p->top]);
}

C program to convert:

1.Postfix to Infix

2.Postfix to Prefix

3.Prefix to Infix

#include<stdio.h>
#include<conio.h>
#include<string.h>
# define MAX 20
typedefstruct stack
{
int data [MAX];
int top ;
}stack;

char str[MAX],stack[MAX];
int top=-1;
void push(char c)
{
stack[++top]=c;
}
char pop()
{

By Nitin Sir
24 | R K D E M Y

return stack[top--];
}
void post_in()
{
inti,n;
char a,b,op;
printf("Enter the postfix expression\n");
gets(str);
gets(str);
n=strlen(str);
for(i=0;i<MAX;i++)
stack[i]=NULL;
printf("Infix expression is:\t");
printf("%c",str[0]);
for(i=1;i<n;i++)
{
if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{
b=pop();
//a=pop();
op=str[i];
printf("%c%c",op,b);
}
else
{
push(str[i]);
}
}
printf("%c",str[top--]);
}
void post_pre()
{
inti,n;
printf("Enter the postfix expression\n");
gets(str);
gets(str);
n=strlen(str);

By Nitin Sir
25 | R K D E M Y

printf("Prefix expression is:\t");


for(i=n-1;i>=0;i--)
printf("%c",str[i]);
}

void pre_in()
{
intn,i;
char a,b,op;
printf("Enter the prefix expression\n");
gets(str);
gets(str);
n=strlen(str);
for(i=0;i<MAX;i++)
stack[i]=NULL;
printf("Infix expression is:\t");
for(i=0;i<n;i++)
{
if(str[i]=='+'||str[i]==''||str[i]=='*'||str[i]=='/')
{
push(str[i]);
}
else
{
op=pop();
a=str[i];
printf("%c%c",a,op);
}
}
printf("%c",str[top--]);
}
void main()
{
int opt;
clrscr();
while(1)
{

By Nitin Sir
26 | R K D E M Y

printf("\n........MENU.......");
printf("\n\t1.Postfix to Infix\n\t2.Postfix to Prefix\n\t3.Prefix to
Infix\n\t4.Exit\n");
scanf("%d",&opt);
switch(opt)
{
case 1:post_in();break;
case 2:post_pre();break;
case 3:pre_in();break;
case 4:exit();
default:printf("Invalid choice");break;
}
}

Introduction to Recursive Functions


• A function that calls itself is called as a recursive function.
• A recursive function must definitely have a condition that exit from calling
the function again.
• Hence there must be a condition that calls the function itself if that
condition is true. If the condition could also be implemented vice versa i.e.
if the condition is false then the function calls itself else if the condition
true, it will exit from the loop calling itself again.

Factorial (n) =1
= n* factorial(n-1)

Write a program to find factorial of a number using recursion


#include <stdio.h>
#include<conio.h>
long int fact(int);
int main()
{
int n,ans;
printf(“Enter a number \n);

By Nitin Sir
27 | R K D E M Y

scanf(“%d”,&n);
ans=fact(n);
printf(“Factorial of %d is %d” ,n,ans);
return 0;
}

long int fact(int x)


{
long int f;
if(x= =1)
{
return(x);
}
else
{
f=x*fact(x-1);
return (f);
}
}

PROGRAM: WRITE A PROGRAM TO FIND VALUE OF Y USING A


RECURSIVE FUNCTION, WHERE Y = XN

#include<stdio.h>
#include<conio.h>
int exponential (int , int);
void main()
{
int n , x , y;
printf(“Enter the value of x and n \n”);
scanf(“%d %d”,&x , &n);
y = exponential(x, n);
printf(“the value of x raise to is %d”,y);
getch();
}
int exponential (int x , int n)
{

By Nitin Sir
28 | R K D E M Y

int ans;
if(n == 1)
{
return x ;
}
else
{
ans= x * exponential(x, n-1);
return(ans);
}
}
OUTPUT:
enter the values of x and n
2
6
the value of x raise to n is 64

WRITE A RECURSIVE FUNCTION TO COMPUTE SUM OF FIRST N


NUMBER BEGINNING WITH 1.

#include<stdio.h>
#include<conio.h>
int compute(int);
void main()
{
int no ,sum;
printf(“Enter a number \n”);
scanf(“%d”,&no);
sum= compute (no);
printf(“sum of number from 1 to n %d”,sum);
getch();
}
int compute (int n)
{
int ans;
if(n = = 1)
{

By Nitin Sir
29 | R K D E M Y

return 1 ;
}
else
{
ans= n + compute(n-1);
return(ans);
}
}
Output :-
Enter a number
10
Sum of 1 to n is 55.

WRITE A RECURSIVE FUNCTION TO COMPUTE FIBONACCI SERIES.

#include<stdio.h>
#include<conio.h>
int fibo(int);
Void main()
{
int n,i,c,f;
printf(“Enter a number of terms”);
scanf(“%d”, &n);
for(c=1;c<=n;c++)
{
f=fibo(i);
printf(“%d”,f);
i++
}
getch();
}
int fibo(int n)
{
if(n==0)
{
return 0;
}

By Nitin Sir
30 | R K D E M Y

else if(n==1)
{
return 1;
}
else
{
return (fibo(n-1) + fibo (n-2));
}
}

By Nitin Sir
31 | R K D E M Y

WRITE A PROGRAM FOR SUM OF DIGITS USE RECURSIVE FUNCTION


TO CALCULATE SUM OF DIGITS OF AN INTEGER

#include <stdio.h>
#include <conio.h>
int sum(int n)
{
if(n==0)
return 0 ;
else
return( n%10 + sum(n/10) ) ;
}

void main()
{
int n,ans ;
printf("Enter the number: ") ;
scanf("%d" , &n) ;
ans= sum(n);
printf("Sum of digits of %d is %d" , n ,ans) ;
getch() ;
}

Output:

Enter the number: 246


Sum of digits of 246 is 12

By Nitin Sir
32 | R K D E M Y

Important Questions
• Write a program in ‘C’ to evaluate a postfix expression. [M-10 Dec-13]
• Explain infix, postfix and prefix expressions with example[ M-6 May-
15]
• Write a c program to convert infix expression into postfix expr [M-10
May-15,May-14].
• Write a c program to convert a polish notation to reverse polish
notation.[M-10 Dec-14].
• Explain ADT. list linear and Non-linear data structure [M-5 DEC
17,DEC 16].
• Explain Stack as an ADT. Give applications of stack [M-5 DEC 16]
• What are various operations on data structure. [M-5 DEC-18]
• Using data structure to check well formatted of parentheses in an
algebraic expression. Write c program for same.
• Explain different types of data structure with example [M-5 May-18,
May-17]
• Write a program in ‘C’ to evaluate postfix expression using stack ADT
[M-10 May-18]
• Explain ADT. List the linear and non linear data structure with
example. [M-5 DEC-17]
• Write a program to convert infix expression into postfix expression.
[M-10, DEC-17, DEC-16]

By Nitin Sir
33 | R K D E M Y

QUEUES
Q.1 What is Queue
• It is a special kind of list, where items are inserted at one end (the
rear) and deleted from the other end(front).
• Queue is FIFO (First In First Out) list.

• Eg:- 1) Queue at railway ticket counter.


2) Queue for bus/rikshaw.
3) Toll-tax bridge.

Q.2 Give ADT for Queue data structure, discuss two


applications of queue data structure. [5M MAY17]
Application of queues:
• Various features of operating system are implemented using a queue.
• Scheduling of processes (round robin algorithm ).
• Spooling(to maintain a queue of jobs to be printed).
• A queue of client processes waiting to receive from the server process.
• Queue is useful in CPU scheduling, Disk scheduling, when multiple
process required CPU at same time.
• In call centre phone system will use queue to hold people calling them
in an order, until a service representative is free.

By Nitin Sir
34 | R K D E M Y

Array representation and implementation of queues:


An array representation of queue requires three entities.
• An array to hold queue elements.
• A variable to hold the index of the front element.
• A variable to hold the index of the rear element.
• A queue data type may be defined formally as follows.

#define MAX 30
typedef struct Queue
{
int data [MAX];
int front , rear;
}Queue;

If the queue is empty then front =-1 and rear=-1;


If the queue is full then rear= MAX-1;
If rear=front then queue contains just one element.
If rear > front then queue is not empty.

Operation on queue implemented


A set of operations on a queue includes:

• Initialize(): initializes a queue by setting the value of rear and front to – 1.


• Enqueue(): inserts an element at the rear end of the queue .
• Dequeue():delete the front element and returns the same.
• Empty(): it returns true (1)if the queue is empty and returns false(0) if
the queue is not empty.
• Full(): it return true (1) if the queues is full and returns false (0) if the
queue is not empty.
• Print(): printing of queue elements.

By Nitin Sir
35 | R K D E M Y

‘C’ function to initialize()


void initialize(Queue *p)
{
p→R= - 1; F=-1
p→F= -1; R=-1
}

‘C ‘ function to check whether queue is empty or not


int empty (Queue *P)
{
if (p→R==-1)
return (1);
else
return (0);
}

‘C’ function to check whether queue is full or not .


int full (Queue *p) 2 3 4
0 1
{ 1 2 30 4 50
if(p→R==MAX-1); 0 0 0
return (1); F R
else
return(0);
}

By Nitin Sir
36 | R K D E M Y

‘C’ function for insertion in queue.


void enqueue (Queue *p, int x)
{
if (p→R == -1)
0 1 2 3 4
{
p→R =p→F=0;
p→data[p→R] = x; F=-1 R=-1
}
else
{ 0 1 2 3 4
1 2 3
p→R=p→R+1; 0 0 0
p→data[p→R]=x; F R
}
}

‘C’ function for deletion.


int dequeue (Q *p)
{
int x;
x=p→data[p→F];
if (p→R==p→F) /* last element */
{ 0 1 2 3 4
p→R=-1; 1
p→F=-1; 0
} F R
else
{ 3 4
0 1 2
p→F = p→F +1 ; 2 3
1
} 0 0 0
return (x); F R
}

By Nitin Sir
37 | R K D E M Y

‘C’ function for printing a queue .


void print (Queue *p)
{
for(i=p→F;i<=p→R;i++)
{
printf(“\n %d”, p→data[i]);
}
}

Write a program to implement linear queue using array. [10M DEC17]

#include<stdio.h>
#include<conio.h>
#define MAX 30
typedef struct Queue
{
int data[MAX] ;
int F, R;
}Queue;
void initialize(Queue *p);
int empty (Queue *P);
int full (Queue *p);
void enqueue (Queue *p, int x);
int dequeue (Queue *p);
void print (Queue * p) ;
void main()
{

int x, ch, n;
Queue q;
init(&q);
do
{
printf(“1-create\n 2-insert\n 3-delete\n 4-Display 5-End\n”)
printf(“Enter your choice n”);
scanf(“%d”,&ch);
switch(ch)

By Nitin Sir
38 | R K D E M Y

{
case 1:
printf(“enter no of elements\n”);
scanf(“%d”,&n);
init(&q);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
}
break;
Case 2:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
Case 3:
if(empty(&q))
{
printf(“queue is empty”);

By Nitin Sir
39 | R K D E M Y

Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
Case 4:
display(&q);
break;
default:
}
}while(ch!=5);
getch();
}
void initialize(Queue *p)
{
p→R=-1;
p→F=-1;
}
int empty (Queue *P)
{
if (p→R == -1)
return(1);
else
return(0);
}

By Nitin Sir
40 | R K D E M Y

int full (Queue *p)


{
if(p→R == MAX-1);
return (1);
else
return(0);
}
void enqueue (Queue *p, int x)
{
if (p→R == -1) /*empty queue */
{
p→R =p→F=0;
p→data[p->R] = x;
}
else
{
p→R=p→R+1;
p→data[p→R]=x;
}
}
int dequeue (Queue *p)
{
int x;
x=p→data[p→F];
if (p→R = = p→F) /* last element */
{
p→R=-1;
p→F=-1;
}
else
{
p→F = p→F+1;
}
return (x);
}
void print (Queue * p)
{

By Nitin Sir
41 | R K D E M Y

int i;

for(i=p→F;i<= p→R;i++)
{
printf(“%d”,p→data[i]);
}
}

Write a menu driven program in C to implement QUEUE ADT the


program should perform following operations. [12M MAY16]

i) Inserting element in the queue


ii) Deleting an element from the queue.
iii) Displaying the queue
iv) Exiting the program

#include<Stdio.h>
#include<conio.h>
#define MAX 30
typedef struct Q
{
int data[MAX] ;
int F, R;
}Q;
void initialize(Q *p) ;
int empty (Q *P) ;
int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{

int x, OP, n;
Q q;
printf(“enter no of elements\n”);
scanf(“%d”,&n);

By Nitin Sir
42 | R K D E M Y

init(&q);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
exit(0);
}
else
{
enqueue(&q,x);
}
}
do
{
printf(“1-Insert an element \n 2-Deleting an element\n 3-
displaying the queue\n 4-Exit the program.\n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1:
printf(“enter the element to be inserted”);
Scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
case 2:

By Nitin Sir
43 | R K D E M Y

if(empty(&q))
{
printf(“queue is empty”);
exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
case 3:
print(&q);
break;
default:
break;
}
}while(op!=4);
getch();
}
void initialize(Q *p)
{
p→R= - 1;
p →F= -1;
}
int empty (Q *P)
{
if (p ->R == -1)
return(1);
else
return(0);
}

int full (Q *p)


{

By Nitin Sir
44 | R K D E M Y

if(p→R == MAX-1);
return (1);
else
return(0);
}
void enqueue (Q *p, int x)
{
if (p→R == -1) /*empty queue */
{
p→R =p→F=0;
p→data [p→R] = x;
}
else
{
p→R=p →R+1;
p →data [p→R]=x;
}
}

int dequeue (Q *p)


{
int x;
x=p→data[p→F];
if (p→R = = p→F) /* last element */
{
p→R=-1;
p→F=-1;
}
else
{
p→F = p→F+1;
}
return (x);
}

void print (Q * p)
{

By Nitin Sir
45 | R K D E M Y

int i;
for (i=p→F; i <= p→R;i++)
{
printf(“%d”,p→data[i]);
}
}

Circular Queues
There is one potential problem with implementation of queue using a simple
array.

The queue may appear to be full although there may be some space in the
queue.

After insertion of five elements in the array


0 1 2 3 4
rear=4; 1 20 3 4 50
0 0 0
front=0 Queue is full
F R
After two successive deletion 0 1 2 3 4
3 4 50
rear=4; 0 0
front=2 Queue is full F R

Queue appears to be full although there is some space in queue.

By Nitin Sir
46 | R K D E M Y

Solution to this last position is connected back to first position.

Whenever rear gets to end of array it is wrapped around to the beginning.

Circular queue is linear data structure in which last element is connected to


first to make circle.

Circular queue implementation


To give a circular movement inside array, whenever we go last element of
the array it should come back to beginning of the array.

i i=(i+1) % MAX
0 (0+1) % 5 =1

1 (1+1)%5 =2

2 (2+1)%5 =3

3 (3+1)%5 =4

4 (4+1)%5 =0 i wrap around to beginning ‘0’

By Nitin Sir
47 | R K D E M Y

Operations on Circular Queue

typedef struct Q
{
int data ;
int R,F;
}Q;

‘C’ function to initialize()

void initialize(Q *p)


{
p→R= -1;
p→F= -1;
}

‘C ‘ function to check whether queue is empty or not


int empty (Q *P)
{
if (p→R == -1)
return(1);
else
return(0);
}
‘C’ function to check whether queue is full or not .
int full (Q *p)
{
if((p→R+1) % MAX ==p→F)
return (1);
else
return(0);
}
‘C’ function for insertion in queue.
void enqueue (Q *p, int x)
{
if (p→R==-1) /*empty queue */
{
p→R =p→F=0;

By Nitin Sir
48 | R K D E M Y

}
else
{
p→R=(p→R+1)%MAX;
}
p→data[p→R] = x;
}

‘C’ function for deletion.


int dequeue (Q * p)
{
int x;
x=p→data[p→F];
if (p→R = = p→F) /* last element */
p→R = p→F=-1;
else
p→F = (p→F+1)%MAX ;
return (x);
}

‘C’ function for printing a queue .


void print (Q * p)
{
int i;
i = p→F; /* start from front */
while (i! =p→R)
{
printf(“\n %d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p→R]);
}

By Nitin Sir
49 | R K D E M Y

Write a program in c to implement a circular queue; the following


operations should be performed by the program.
1. Create 2. Insert 3. Delete 4. Display 5. Exit
Write a program to implement circular queue using arrays. [10M
MAY18, 10M MAY15, 10M DEC15]

#include<stdio.h>
#include<conio.h>
#define max 30
typedef struct Q
{
int data[MAX] ;
int F, R
}Q;
void initialize(Q *p) ;
Int empty (Q *P) ;
Int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{
int x, op, n;
Q q;
init(&q);
do
{
Printf(“1-create\n 2-insert\n 3-delete\n 4-print\n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1: printf(“enter no of elements\n”);
scanf(“%d”,&n);
printf(“enter the data\n”);
for(i=0;i<n;i++)
{

By Nitin Sir
50 | R K D E M Y

scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
}
break;
Case 2:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))
{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
Case 3:
if(empty(&q))
{
printf(“queue is empty”);
Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;

By Nitin Sir
51 | R K D E M Y

Case 4:
print(&q);
break;
default:
break;
}
}while(op!=5);
getch();
}
void initialize(Q *p)
{
p-→R= - 1;
p →F= -1;
}
int empty (Q *P)
{
if (p→R == -1)
return(1);
else
return(0);
}

Int full (Q *p)


{
if((p→R+1) % MAX ==p→F)
return (1);
else
return(0);
}

void enqueue (Q *p, int x)


{
if (p→F== -1 ) /*empty queue */
{
p→R =p→F=0;
}
else

By Nitin Sir
52 | R K D E M Y

{
p→R=(p→R+1)%MAX;
}
p→data[p→R] =
x;
}

int dequeue (Q * p)
{
int x;
x=p→data[p→F];
if (p→R = = p→F) /* last element */
p→R = p→F=-1;
else
p→F = (p→F+1)%MAX
;
return (X);
}

void print (Q * p)
{
int i;
i = p→ F; /* start from front */
while ( i! =p→R)
{
printf(“%d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p-R]);
}

By Nitin Sir
53 | R K D E M Y

Priority Queue

• priority queue is an ordered list of elements.


• In priority queue services is provided on the basis of priority based on
urgency of need.
• In a normal queue service is provided on the basis “first come first
served” where as in priority queue service is provided on the basis of
priority.
• An element with higher priority is processed before other element with
lowest priority.
• An element with equal priority are process on “first-come-first-served”
basis.
• example: -
1) Hospital waiting room
A patient with more fatal problem will be admitted before other
patients.
2) In long term scheduling of jobs in a computer.
Short processes are given priority over long process to improve
response time.

Priority queue can be implemented by

1. Circular array
2. Linked list

1. Implementation of priority queue using circular array

void initialize(Q *p)


{
p→R= - 1;
p →F= -1;
}
int empty (Q *P)
{
if (p→R == -1)
return(1);
else
return(0);
}

By Nitin Sir
54 | R K D E M Y

Int full (Q *p)


{
if((p→R+1) % MAX ==p→F)
return (1);
else
return(0);
}

void enqueue (queue *p, int x)


{
int i;
if (full (p))
{
printf(“overflow\n”);
exit(0);
}
else
{
if (empty(p))
{
P→rear = P→front = 0;
P→data[0]= x;
}
else
{
i= p→rear;
while(x >p→data[i]);
{
p→data[(i+1)% max]= p→data[i];
i=(i-1+max)%max;
if ((i+1)%MAX = = P→ front)
break;
}
i =(i+1)%max /*insert*/
/*re-adjust error*/
p→data[i]= x;

By Nitin Sir
55 | R K D E M Y

p→rear=(p→rear + 1)%max;
}

Int dequeue (Q * p)
{
int x;
x=p→ data[p→F];
if (p→R = = p→F)
{
p→F=-1;
p→R=-1;
}
else
{
p→F = (p→F+1)%MAX ;
}
return (X);
}

void print (Q * p)
{
int i;
i = p→F; /* start from front */
while (i! =p→R)
{
printf(“\n %d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p→R]);
}

By Nitin Sir
56 | R K D E M Y

Write a c program to implement priority queue using array, the program


should perform following operations. [12M DE 18]

i)Insert in a priority queue ii) Delete from a queue

iii) Display elements of a queue.

#include<stdio.h>
#include<conio.h>
#define max 30
typedef struct Q
{
int data[MAX] ;
int F, R
}Q;
void initialize(Q *p) ;
Int empty (Q *P) ;
Int full (Q *p) ;
void enqueue (Q *p, int x);
int dequeue (Q *p);
void print (Q * p) ;
void main()
{
int x, op, n;
Q q;
init(&q);
do
{
printf(“1- Insert in a priority queue \n 2-delete\n 3-display\n 4-
exit \n”)
printf(“Enter your choice n”);
scanf(“%d”,&op);
switch(op)
{
case 1:
printf(“enter the element to be inserted”);
scanf(“%d”,&x);
if (full(&q))

By Nitin Sir
57 | R K D E M Y

{
printf(“queue is full\n”);
Exit(0);
}
else
{
enqueue(&q,x);
}
break;
case 2:
if(empty(&q))
{
printf(“queue is empty”);
Exit(0);
}
else
{
x=dequeue(&q);
printf(“element=%d”,x);
}
break;
case 3:
print(&q);
break;
default:
break;
}
}while(op!=4);
getch();
}

void initialize(Q *p)


{
p→R= - 1;
p →F= -1;
}

By Nitin Sir
58 | R K D E M Y

Int empty (Q *P)


{
if (p→R == -1)
return(1);
else
return(0);
}

Int full (Q *p)


{
if((p→R+1) % MAX ==p→F)
return (1);
else
return(0);
}

void enqueue (queue *p, int x)


{
int i;
if (full (p))
{
printf(“overflow\n”);
exit(0);
}
Else if (empty(p))
{
P→rear = P→front = 0;
P→data[0]= x;
}
else
{
i= P→rear;
while(x >p→data[i]);
{
P→data[(i+1)% max]= P→data[i];
i=(i-1+max)%max;
if ((i+1)%MAX = = P→ front)

By Nitin Sir
59 | R K D E M Y

break;
}
i =(i+1)%max /*insert*/
/*re-adjust error*/
P→data[i]= x;
P→rear=(P→rear + 1)%max;
}
}

Int dequeue (Q * p)
{
int x;
x=p→ data[p→F];
if (p→R = = p→F)
{
p→F=-1;
p→R=-1;
}
else
{
p→F = (p→F+1)%MAX ;
}
return (X);
}

void print (Q * p)
{
int i;
i = p→F; /* start from front */
while (i! =p→R)
{
printf(“\n %d”, p→data[i]);
i=(i+1)%MAX ;
}
printf(“%d”, p→data[p→R]);
}

By Nitin Sir
60 | R K D E M Y

Explain circular queue and double ended queue with example [10M
DEC16].

Dequeue
It is double ended queue.

In a dequeue insertion as well as deletion can be carried out either at the


rear end or front end.

Dequeue is classified into two types:

▪ Input restricted dequeue: -


1) Insertion of an element at the rear.
2) Deletion of an element from front.
3) Deletion of an element from rear end.

▪ Output restricted dequeue: -


1) Deletion of an element from front end.
2) Insertion of an element at from rear end.
3) Insertion of an element at the front end.

Operation on dequeue :-

• init() – make the queue empty.


• empty() – determine if queue is empty.
• full() – determine if queue is full.
• enqueueF() – insert an element at the front end.
• dequeueR() – delete rear element.
• dequeueF() – delete front element.
• printf() – print element of queue.

By Nitin Sir
61 | R K D E M Y

1. Write a program in c to implement Queue ADT using linked list to


perform the following operations [10M MAY18]
i) Insert a node in the queue ii)Delete a node from quque
iii) Display quque elements

2. Write a program to implement circular queue using arrays. [10M


MAY18, 10M MAY15, 10M DEC15]

3. Write a c program to implement priority queue using array, the


program should perform following operations. [12M DE 18]
i)Insert in a priority queue ii) Delete from a queue

iii) Display elements of a queue.

4. Write a program to implement linear queue using array. [10 DEC17]

5. Give ADT for Queue data structure, discuss two applications of queue
data structure.[5M MAY17]

6. Write a menu driven program in C to implement QUEUE ADT the


program should perform following operations. [12M MAY16]
v) Inserting element in the queue
vi) Deleting an element from the queue.
vii) Displaying the queue
viii) Exiting the program

7. Explain circular queue and double ended queue with example [10M
DEC16].

8. Write an algorithm to implement queue using array [10M


MAY18,DEC18,DEC17 (IT)]

9. Write an algorithm to implement priority queue using array [10M


May18 (IT)]

10. Write an algorithm to create doubly linked list and display list
[10M May-18 (IT)]

11. Write an algorithm for following operation on Doubly linked list.


[10 M DEC18 (IT)]
a. Insertion
b. Deletion
c. Traversal

By Nitin Sir
62 | R K D E M Y

12. Write an algorithm for following operation on singly linked list.


[10 M DEC17 (IT)]
a. Insertion
b. Deletion
c. Traversal

By Nitin Sir
63 | R K D E M Y

Linked list

• Linked List is Series of Nodes.


• Each node Consist of two Parts viz Data Part & Pointer Part.
• Pointer Part stores the address of the next node.

Data next

• It is a data Structure which consists of group of nodes that forms a


sequence.
• Linked list comprise of group or list of nodes in which each node have
link to next node to form a chain

What is linked list? State its advantage, Explain its types [3M DEC-18]

Advantages of linked list


• Linked List is Dynamic data Structure.
• Linked List can grow and shrink during run time.
• Insertion and Deletion Operations are Easier.
• Efficient Memory Utilization, i.e no need to pre-allocate memory
• Faster Access time, can be expanded in constant time without
memory overhead
• Linear Data Structures such as Stack, Queue can be easily implemeted
using Linked list

By Nitin Sir
64 | R K D E M Y

Disadvantages of Linked List


1. Wastage of Memory
Pointer Requires extra memory for storage.

2. No Random Access
In array we can access nth element easily just by using a[n].
In Linked list no random access is given to user, we have to access
each node sequentially.

3 . Time Complexity
Array can be randomly accessed , while the Linked list cannot be
accessed Randomly.

4. Reverse Traversing is difficult


In case if we are using singly linked list then it is very difficult to
traverse linked list from end.

5. Heap Space Restriction


If there is insufficient space in heap then it won’t create any
memory.

Linked list as an ADT


Structure in “c” can be used to define a node.
Address of the successor node can be stored in pointer variable.

Linked list is a self referential structure in “c”. each node has variable to store
data and next field store the address of next field.

typedef struct node


{
int data;
struct node *next;
}node;

By Nitin Sir
65 | R K D E M Y

Types of linked list

1. Singly Linked List


• In this type of Linked List two successive nodes are linked
together in linear fashion .
• Each Node contain address of the next node to be followed.
• In Singly Linked List only Linear or Forward
Sequential movement is possible

2. Doubly linked list

• In this type of linked list each node holds two pointer field.
• In doubly linked list address of next as well as preceding element
are linked with current node.
Head

3. Circular linked list


• In a circular list the first and last element are adjacent.
• A linked list can be made circular by storing the address of first
node in next field of last node.

What is the difference between Singly Linked List and Doubly Linked
List?
• Each element in the singly linked list contains a reference to the next
element in the list, while each element in the doubly linked list
contains references to the next element as well as the previous
element in the list.

By Nitin Sir
66 | R K D E M Y

• Doubly linked lists require more space for each element in the list and
elementary operations such as insertion and deletion is more complex
since they have to deal with two references.
• But doubly link lists allow easier manipulation since it allows
traversing the list in forward and backward directions.

1. Singly Linked List


• In this type of Linked List two successive nodes are linked
together in linear fashion.

• Each Node will store the data and address of the next node to be
followed.

• In Singly Linked List only Linear or Forward


Sequential movement is possible.

• Elements are accessed sequentially , no direct access is allowed.

• Last Node have successor reference as “NULL“.

Head

Operation on linked list

1. Traversing
2. Creating
3. Inserting
4. Deleting
5. Merging
6. Sorting
7. Searching

By Nitin Sir
67 | R K D E M Y

Insertion of node in Singly Linked list


Inserting a new Item, say x has three Situations.
1. Insertion at the front of the list.
2. Insertion at the middle of the list.
3. Insertion at the end of the list.

1. Inserting a node at beginning of a linked list

Algorithm
1. Obtain space for new node.
2. Assign data to the data field of the new node.
3. Set the next field of the new node to the beginning of the linked list.
4. Change the reference pointer of the linked list to point to the new
node.

Inserting the new node after node N1


Algorithm
1. Obtain space for new node.
2. Assign value to its data field.
3. Search for the node n1.
4. Set the next field of new node to point to n1→next.
5. Set the next field of n1 to point to the new node.

By Nitin Sir
68 | R K D E M Y

node *insert(node *head, int x, int key)


{
/* if key is -1 then x is to be inserted at front
node *p,*q;
/* space for a new node
p=(node*) malloc(sizeof(node));
p->data=x;
if(head→data==key)
{
/* insert the node at the front of the list.
p->next=head;
head=p;
}
else
{
/* search key in the linked list
q=head;
while(key!=q->data && q!=null )
{
q=q->next;
}
if(q!=null)
{
/* if key is found
p->next=q->next;
q->next=p;
}
}
}

Inserting an item at the end of linked list:

5 10 15 x

Algorithm:

By Nitin Sir
69 | R K D E M Y

1. Allocate memory for new node.


2. Assign value to data field of new node.
3. If (head==NULL) then head=p; got step 6.
4. Position a pointer q on last node by traversing the linked list.
5. Store the address of new node in next field of node q.
6. Stop.

node *insert_end (node *head, int x)


{
node *p,*q;
/* space for a new node
p=(node*) malloc(sizeof(node));
p→data=x;
p→next=NULL;
if(head==NULL)
{
return(p);
}
else
{
q=head;
while(q→next!=NULL)
{
q=q→next;
}
q→next=p;
return(head);
}

Inserting an element x at location ‘LOC’

node *insert_loc(nod *head, int x, int loc)


{
node *p,*q;
inti;
p=(node*) malloc(sizeof(node));

By Nitin Sir
70 | R K D E M Y

p→data=x;
p→next=NULL;
if(loc==1)
{
p→next=head;
return(p);
}
else
{
q=head;
for(i=1;i<=loc-1;i++)
{
if(q!=NULL)
{
q=q→next;
}
else
{
printf(“\n Overflow);
return(head);
}
p→next=q→next;
q→next=p;
return(head);
}
}

Delete a node of a linked list


Deleting a node has three cases
1. Deleting first node
2. Deleting last node
3. Deleting from middle of list

1. Deleting the first node

5 10 15

By Nitin Sir
71 | R K D E M Y

Algorithm
– Store the address of the first node in a pointer variable, say p.
– Move the head to the next node.
– Free the node whose address is stored in the pointer variable P.

Algorithm Deleting a node from the middle


– Store the address of preceding node in a pointer variable, say p.
– Node to be deleted is marked as key node.
– Store the address of the key node in a pointer variable q, so that it can
be free.
– Make the successor of key node as successor of the node pointed by p.
– Free the node whose address is stored in the pointer variable q.

node * delete(node *head, int x)


{
node *p,*q;
if(x==head→data)
{
p=head;
head=head-->next;
free(p);
}
else
{
while(x!=(p→next)→data && p→next!=null)
{
p=p→next;
}
if(p→next!=null)
{
q=p→next;
p→next=(p→next)→next;
free(q);
}
}
return(head);
}

By Nitin Sir
72 | R K D E M Y

Deleting of last node in linked list

5 10 15

Algorithm
2. If the first node itself is the last node then [make the linked list empty]
3. Position a pointer q on first node
4. Traverse in the list till q reach to previous node of last node
5. Position a pointer ‘p’ on last node
6. Free node whose address is store in pointer ‘p’
7. Set q→ next to null.

node *delete_last(node *head)


{
node *p, *q;
If(head→next==NULL)
{
free(head);
return(head);
}
q=head;
While(q→next→next !=NULL)
{
q=q→next;
}
p=q→next;
free(p);
q→next=NULL;
return(head);
}

By Nitin Sir
73 | R K D E M Y

Searching a data in Linked list

Algorithm
1. p=head
2. If the data in node p is x then
End search with success i.e. return(1)
3.Continue searching p=p→next.
4.If linked list end then end with failure i.e. return(0)
5.go to step 2
6.stop.

int search(node *head, int x)


{
node *p;
p=head;
if(head→data==x)
{
return(1);
}
else
{
p=p→next;
while(p!=null)
{
if(p-->data=x)
return(1);
p=p-->next;
}
return(0);
}
}

Counting number of nodes in linked list

5 10 15

By Nitin Sir
74 | R K D E M Y

int count(node *p)


{
inti;
i=0;
while(p!=NULL)
{
i=i+1;
p=p->next;
}
return(i);
}

Write a program to create linked list


#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node *next;
}node;
void main()
{
node *Head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
Head=(node*)malloc(sizeof(node));
//read the data in 1st node
scanf(“%d”, &(Head->data));
Head->next=Null;
p=Head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=NULL;
scanf(“%d”, &(p->data));

By Nitin Sir
75 | R K D E M Y

}
getch();
}

Write a ‘C’ program to create a single linked list which support following
operations. [10M May-18, Dec-18,

1) creating a linked list


2) inserting a node in the beginning
3) Insert a node at the end
4) delete a specific node
5) Display list

#include<stdio.h>
#include<conio.h>
typedef struct node
{
Int data;
Struct node *next;
}node;

node* create();
node* insert_b(node * head, intX);
node* insert_e(node * head, intx);
node* delete(node * head);
void print(node* head);
void main()
{
int op, x;
node * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&op);
switch(op)
{

case1:

By Nitin Sir
76 | R K D E M Y

head=create();
break;
case2:
printf(“enter the data to be inserted\n);
scanf(“%d”,&x);
head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);
head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:

}
}while(op!=6);
getch();
}
void create ()
{
node *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(node*)malloc(sizeof(node));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=null;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));

By Nitin Sir
77 | R K D E M Y

p=p->next;
p->next=NULL;
scanf(“%d”, &(p->data));
}
}

node *insert_b(node *head, int x)


{
node *p;
/* space for a new node
p=(node*) malloc(sizeof(node));
p→data=x;
/* insert the node at the front of the list.
p→next=head;
head=p;
}
node *insert_e (node *head, int x)
{
node *p,*q;
/* space for a new node
p=(node*) malloc(sizeof(node));
p→data=x;
p→next=NULL;
if(head==NULL)
{
return(p);
}
else
{
q=head;
while(q→next !=NULL)
{
q=q→next;
}
q→next=p;
return(head);
}

By Nitin Sir
78 | R K D E M Y

node * delete(node *head, int x)


{
node *p,*q;
if(x==head→data)
{
p=head;
head=head→next;
free(p);
}
else
{
while(x!=(p→next)→ data && p→next!=null)
{
p=p→next;
}
if(p→next!=null)
{
q=p→next;
p→next=(p→next)→next;
free(q);
}
}
return(head);
}

void print(node * head)


{
node *p;
for(p=head; p!=null; p=p→next)
{
printf(“%d”, p→data);
}
}

By Nitin Sir
79 | R K D E M Y

Circular Linked list


• In circular linked list, last node is connected back to the first
node.
• Queue data structure can be implemented using a circular linked
list.
• Front node can be accessed through the root node.

Operation on circular linked list:


1) Insertion
2) Deletion
3) Display

Insertion of a node at the front of circular linked list

5 10 15

node * Insert_b(node *head, int x)


{
node*p,*q;
p=(node*)malloc(size of (node);
p→data=x;
if(head==NULL)
{
head= p;
head→next=head;
}
else
{
q=head;
while(q→next != head)
{

By Nitin Sir
80 | R K D E M Y

q=q→next;
}
q→next=p;
p→next=head;
head= p;
return(head);
}
}

Insertion of a node at the end of circular linked

5 10 15

node * insert_e(node *head, int x)


{
node*p,*q;
p=(node*)malloc(size of (node);
p→data=x;
if(head==NULL)
{
head= p;
p→next=p;
}
else
{
q=head;
while(q→next != head)
{
q=q→next;
}
q→next=p;
p→next=head;
return(head);

By Nitin Sir
81 | R K D E M Y

}
}

Deletion of node in circular linked list

Delete a beginning node

5 10 15

p
void delete_b(node * head)
{
node *p;
if(head→next==head);
{
p=head;
free(p);
head=null
return (head);
}
else
{
q=head;
while (q→next!=head)
{
q=q→next;
}
p=head;
q→next=head→next;
head=head→next;
free(p);
return (head);
}
}

By Nitin Sir
82 | R K D E M Y

8. Delete a specific node

void delete(node * head, int key)


{
node *p,*q;
if(head→data==key);
{
free(p);
head=null
return (head);
}
else
{
q=head;
while (q→next→data !=key)
{
q=q→next;
}
p=q→next;
q→next=p→next;
free(p);
return (head);
}
}

3. Delete a end node

5 10 15

void delete_e(node * head)

By Nitin Sir
83 | R K D E M Y

{
node *p;
if(head→data==head);
{
free(p);
head=null
return (head);
}
else
{
q=head;
while ((q→next)→next!=head)
{
q=q→next;
}
p=q→next;
q→next=null;
free(p);
return (head);
}
}

Display data in a circular linked list

void print(node * head)


{
node *p;
If(head!=null)
{
p=head;
while(p→next!=head);
{
printf(“%d”,p→data);
p=p→next;
}
printf(“%d”,p→data);
}

By Nitin Sir
84 | R K D E M Y

What is circular queue? Write a program in c to implement it. [M-10


May-2015]
#include<stdio.h>
#include<conio.h>
typedef struct node
{
Int data;
Struct node*next;
}node;

node* create();
node* insert_b(node * head, intX);
node* insert_e(node * head, intx);
node* delete(node * head);
void print(node* head);
void main()
{
int op, x;
node * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&top);
switch(op)
{

case1:
head=create();
break;
case2:
printf(“enter the data to be inserted\n);
scanf(“%d”,&x);
Head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);

By Nitin Sir
85 | R K D E M Y

head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:

}
}while(op!=6);
getch();
}

void create ()
{
node *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(node*)malloc(sizeof(node));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=head;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=head;
scanf(“%d”, &(p->data));
}

By Nitin Sir
86 | R K D E M Y

node *insert_b(node *head, int x)


{
node*p,*q;
p=(node*)malloc(size of (node);
p→data=x;
if(head==NULL)
{
head= p;
p→next=p;
}
else
{
q=head;
while(q→next != head)
{
q=q→next;
}
q→next=p;
p→next=head;
head=p;
return(head);
}
}
node *insert_e (node *head, int x)
{
node*p,*q;
p=(node*)malloc(size of (node);
p→data=x;
if(head==NULL)
{
head= p;
p→next=p;
}
else
{

By Nitin Sir
87 | R K D E M Y

q=head;
while(q→next != head)
{
q=q→next;
}
q→next=p;
p→next=head;
return(head);
}
}

void delete(node * head, int key)


{
node *p,*q;
if(head→data==key);
{
free(p);
head=null
return (head);
}
else
{
q=head;
while (q→next→data !=key)
{
q=q→next;
}
p=q→next;
q→next=p→next;
free(p);
return (head);
}
}

void print(node * head)


{
node *p;

By Nitin Sir
88 | R K D E M Y

If(head!=null)
{
p=head;
while(p→next!=head);
{
printf(“%d”,p→data);
p=p→next;
}
printf(“%d”,p→data);
}
}

Doubly Linked List :


In Doubly Linked List , each node contain three fields .
• One for storing the data.
• Another field for storing address of next node to be followed
• Third field contain address of previous node linked to it.
• In DLL we can access both next as well as previous data using “next
link” and “previous link“.
• Traversing in both direction is allowed.

Doubly linked list


typedef struct dnode
{
Int data;
struct dnode *next, *prev;
}dnode;

By Nitin Sir
89 | R K D E M Y

Creation of doubly linked list.

Algorithm for insertion of x.


1. dnode *p, *q;
2. Acquire space for the new node.
3. p=(dnode*) malloc(sizeof(dnode));
4. Store x in the newly acquired node p→data=x
5. If head == null then go to step 6 else step 8
6. Change reference of head to new node [Head=p;]
7. Make previous and next field as NULL.
8. [head→prev=head→next=NULL]
9. Set new node next field to head, [p→next=head]
10. Set previous filed to new node p[head→prev=p]
11. Set previous field of new node to NULL, [p→prev=NULL;]
12. Change reference of head to new node [Head=p;]

1. Inserting node at the begining


dnode * insert_b(dnode *head,int x)
{
dnode *p;
p=(dnode*)malloc(sizeof(dnode));
p→data=x;
If(head ==NULL)
{

By Nitin Sir
90 | R K D E M Y

head =p;
head→next=head→prev=NULL;
}
else
{
p→next=head;
head→prev=p;
p→prev=NULL;
head=p;
}
return (head);
}

Insert In between of DLL

Algorithm for insertion of x after key node

By Nitin Sir
91 | R K D E M Y

1. dnode *p, *q;


2. Acquire space for the new node.
3. p=(dnode*) malloc(sizeof(dnode));
4. Store x in the newly acquired node p→data=x
5. Assign pointer q to head node [ q→head]
6. Traverse till q→data ! key and q!=null
7. Set next filed of new node as key node next [p→next=q→next;
8. Set previous field of new node as key node [p→prev=q;]
9. (p→next)→prev=p;
10. (p→prev)→next=p;

dnode * insert_in(dnode *head,int x,int key)


{
dnode *p,*q;
p=(dnode*)malloc(sizeof(dnode));
p→data=x;
q=head;
while(q→data!=key && q!=NULL)
{
q=q→next;
}
If(q→data==key)
{
p→next=q→next;
p→prev=q;
(p→next)→prev=p;
(p→prev)→next=p;
}
return(head);
}

Insert at end

dnode * insert_e(dnode *head, int x)


{
dnode *p,*q;
P=(dnode*)malloc(sizeof(dnode));

By Nitin Sir
92 | R K D E M Y

P→data=x;
If(head==NULL)
{
head=p;
head→next=head→prev=NULL;
}
else
{
q=head;
While(q→next!=NULL)
{
q=q→next;
}
q→next=p;
p→prev=q;
p→next=NULL;
}
return(head);
}

By Nitin Sir
93 | R K D E M Y

Deletion of a node

Deletion of a node pointed by p


dnode * delete(dnode *head, dnode *p)
{
dnode *p,*q;
If(p==head)
{
p→next→prev=NULL;
Head=p→next;
Free(p);
return(p);
}
P→prev→next=p→next;
if(q→next!=NULL)
{
p→next→prev=p→prev;
}
free(p);
return(head);
}

By Nitin Sir
94 | R K D E M Y

Write a c program in ‘C’ to implement doubly link-list with methods insert,


delete and search. [M-10 May-14]
Write a c program in ‘C’ to implement doubly link-list, perform following
operations.
1. Insert node in the beginning
2. Insert node at end
3. Delete a node from end
4. Display the list.

#include<stdio.h>
#include<conio.h>
typedef struct dnode
{
Int data;
struct dnode *next, *prev;
}dnode;

dnode* create();
dnode* insert_b(dnode * head, intX);
dnode* insert_e(dnode * head, intx);
dnode* delete(dnode * head);
void print(dnode* head);
void main()
{
int op, x;
dnode * head=null;
do
{
printf(“1-create\n 2-insert in beginning \n 3-Insert at end\n 4-
delete a specific\n 5-display\n 6-quit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&top);
switch(op)
{

case1:
head=create();
break;
case2:
printf(“enter the data to be inserted\n);

By Nitin Sir
95 | R K D E M Y

scanf(“%d”,&x);
Head=insert_b(head, x);
break;
case3:
printf(“enter data to be inserted\n”);
scanf(“%d”,&x);
head=insert_e(head, x);
break;
case4:
printf(“enter the data to be deleted\n”);
scanf(“%d”,&x);
head=delete(head,x);
break;
case5:
print(head);
break;
default:

}
}while(op!=6);
getch();
}
void create ()
{
dnode *head, *p;
int n, x, i;
printf(“ Enter no of items”);
scanf(“%d”, &n);
head=(dnode*)malloc(sizeof(dnode));
//read the data in 1st node
scanf(“%d”, &(head->data));
head->next=head;
p=head;
for(i=1;i<n;i++)
{
p->next=(node*)malloc(sizeof(node));
p=p->next;
p->next=head;
scanf(“%d”, &(p->data));
}

By Nitin Sir
96 | R K D E M Y

LINKED REPRESENTATION OF STACK


Stack can be represented through singly connected linked list.

typedef struct node


{
int data ;
struct node *next;
} node;

Initilize a stack

void init (stack **T)


{
*T= Null;
}
Insert data in stack

void push(stack **T, intX)

stack *P;

p=(stack*) malloc (size of (stack));

P→data= X;

P→next= *T;

*T= P;

Delete the top element of a stack

By Nitin Sir
97 | R K D E M Y

Int top (stack **T)

Int x;

Stack *p;

P= *T;

*T= P→next;

x= P→data;

free(p);

return (X);

int empty(stack *top)

if (Top= = Null)

{
return (1);
}
else
{
return (0);
}
}

Write a program to reverse a string represented using stack

# include<stdio.h>
#include<conio.h>
typedef struct stack
{
char data;
struct stack *next;
}

By Nitin Sir
98 | R K D E M Y

void init ( stack **);

int empty (stack *);

char pop (stack **);

void push (stack **, char);

void main()

{
Stack *top;
char x;
init(&top);
printf(“enter the spring\n”)
While ((x=getchar())!=’\n’)
{
Push(&top, x);
}
while(!empty (top))
{
x =pop(&top);
printf(“%c”, x);
}
void init(stack**T)
{
*T=NULL;
}
Int empty (stack *top)
{
If(top= = NULL)
return(1);
return(0);
}
void push(stack**T, char x)
{
stack *p;
p=(stack*)malloc(sizeof(stack));
P→data= x;

By Nitin Sir
99 | R K D E M Y

P→next= *T;
*T=P;
}
char pop (stack**T)
{
char x;
Stack *P;
P=*T;
*T= P→next;
X= P→data;
free(p);
return(x);
}

Representation of queue using linked list


A Queue can be represented by a linked structure of element.
Each element is stored in node & memory acquired during runtime using
malloc() fuction.

Write a program, for various operations on queue using circular linked list.
#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node*next;
}node;
Void int(node **R);
Void enqueuer(node **R,int x);
Int dequeue(node **R);
Int empty(node **R);
Void print(node **R);
Void main()
{
Int x,ch;
Int n=0,i;
node *rear;

By Nitin Sir
100 | R K D E M Y

init(&rear);
do
{
Printf(“1.Insert\n2.deletion\3.print\n4.Quit”);
Printf(“Enter your option\n’);
Scanf(“%d”,&ch);
Switch(ch)
{
Case 1:
Printf (“Nuumber of elements to be inserted”);
Scanf(“%d”,&n);
For (!=0;1<n;!++)
{
Scanf(“%d”,&X);
Enqueue (&rear,X);
}
Break;
Case 2:
If(!empty(&rear))
{
X= dequeuer(&rear);
Printf(“\element delete=%d”,x);
}
Else
{
Printf(“underflow…”);
}
Break;
Case 3:
Print(&rear);
Break;
Default:

}
}while(ch!=4);
getch();
}
Void enqueuer(node**R, intX)
{
node*P;

By Nitin Sir
101 | R K D E M Y

P→data=X;
If(empty(*R))
{
P→next=p;
*R=P;
}
else
{
P→next=(*R)→next;
(*R)→next)=P;
*R=P;
}
}
Int dequeue (node**R)
{
Int X;
node*P;
P=(*R)→next;
P→data=x;
If(P→next==P)
{
*R=NULL;
free(p);
return(X);
}
(*R)→next= P→next;
Free(P);
Return(X);
}
Void print(node*rear)
{
node*P;
If (!empty(rear))
{
P=rear→next;
While(P!=rear)
{
Printf(“%d”,P→data);
P=P→next;
}
Printf(”%d”,P→data);
}

By Nitin Sir
102 | R K D E M Y

}
Int empty(node*P)
{
If (P→nexrt=== -1)
{
return(1);
}
return(0);
}

Important Questions
• Write a c program to implement singly list which supports the
following operation.
• Insert node in the beginning.
• Insert a node in the end
• Insert a node after a specific node.
• Deleting a specific node.
• Displaying the list.
• State difference between singly and doubly linked list along with
application.
• What is circular queue? Write a program in c to implement it. [M-10
May-2015]
• Write a c program in ‘C’ to implement doubly link-list with methods
insert, delete and search. [M-10 May-14]
• What is linked list and explain its types [3M May-18]
• Insert the following elements in AVL tree 44,17,32,78,50,88,48,62,54
explain different types of rotations that can be used. [10M May-18]
• Explain different types of tree traversal techniques with example, also
write recursive function for each traversal technique. [10M May-18]
• Write a function in c to implement binary search [5M Dec-18]
• What are expression trees ? what are its advantages ? Derive the
expression tree for following algebraic expression ?
(a + (b/c) )*((d/e)-f) [8M DEC-18]

• Give postorder and inorder traversal of a binary tree , construct the


tree [10M DEC-18]
Postorder D E F B G L J K H C A
Inorder D B F E A G C L J H K

By Nitin Sir
103 | R K D E M Y

• Write a short not on AVL tree and expression tree [10M DEC-17]
• Explain AVL tree, Insert the following elements in AVL search tree
63, 52,49,83, 92, 29, 23, 54, 13, 99 [10M DEC-17]
• Explain Threaded Binary Tree [5M DEC-17]
• Describe expression Tree with example
• Write a program in c to delete a node from a Binary search tree. The
program should consider the all the possible cases.

• IT
What is linked list? State its advantage, Explain its types [3M DEC-18,
May-18]
• Define minimum spanning tree. List techniques to compute minimum
spanning tree. [3M May-18]
• Define expression tree with example. [3M DEC-18, May-18]
• Write an algorithm to create doubly linked list and display it [10M
May-18]
• Define binary search tree ? Explain different operation on binary
search tree with example. [10M May-18]
• Define binary search tree ? find inorder, preorder and postorder of
following binary tree. [10M DEC-18]


• Define binary search tree ? write an algorithm for following operation
• Insertion
• Deletion

• What is minimum spanning tree? Draw MST using kruskal’s and prims
algorithm. [10M May-18]
• What is minimum spanning tree? Explain kruskal’s algorithm with an
example. [10M May-18]

By Nitin Sir
104 | R K D E M Y

• Explain binary search tree. Construct binary search tree for following
elements 47,12,75, 88, 90, 73, 57, 1, 85, 50, 62 [10M DEC-18]

Algorithm
Queue is Full
begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
end procedure

Queue is Empty
begin procedure isempty

if front is less than MIN OR front is greater than rear


return true
else
return false
endif

end procedure

procedure enqueue(data)

if queue is full
return overflow
endif

rear ← rear + 1
queue[rear] ← data
return true

end procedure

Insert Operation

Step 1: If REAR >= SIZE – 1 then


Write “Queue is Overflow”
Step 2: REAR = REAR + 1
Step 3: QUEUE [REAR] = X
Step 4: If FRONT = -1 then
FRONT = 0

By Nitin Sir
105 | R K D E M Y

TREE
Introduction to Trees
A tree is a collection of elements called “nodes”,one of which is distinguished
as a root say r ,

The root can have zero or more nonempty subtrees T1 , T2 ,… Tk each of whose
roots are connected by a directed edge from r.

The root of each subtree is said to be a child of r and r is parent of each


subtree root.

Root: it is a special node in a tree structure and the entire tree is referenced
through it. This mode does not have a parent.

Parent: it is an immediate predecessor of a node ,. In the fig A is the parent


of B,C,D.

Child: All immediate successor of a node are its children. In the fig B,C and D
are the children of A.

Siblings: nodes with the same parent are siblings H,I and J are siblings as
they are children of the same parent D.
Path: it is number of successive edges from source node to destination node.

Degree of a node:
The degree of a node is a number of children of a node

By Nitin Sir
106 | R K D E M Y

A node of degree 2 and B node of degree 3.

Leaf node: A node of degree 0 is also know as a leaf node. A leaf node is a
terminal node and it has no children.

Level: The level of a node in a binary tree is defined as:


The root of the tree has level 0

Depth: The Depth of a binary tree is the maximum level of any node in the
tree. This is equal to the node in the tree. This is equal to the longest path
from the root to any leaf node.

Binary Tree
A tree is binary if each node of the tree can have maximum of two children.
Children of a node of binary tree are ordered. One child is called the “left”
child and the other is called “right” child.

Linked Representation of a Binary Tree

Linked representation of a binary tree is more efficient than array


representation. A node of a binary tree consist of three fields as shown below
• Data
• Address of the left child
• Address of the right child

Left Data Right


Syntax :
typedef struct node
{
int data;

By Nitin Sir
107 | R K D E M Y

struct node*left , *right;


}node;

By Nitin Sir
108 | R K D E M Y

Types of Binary Tree


1. Full Binary Tree
A binary tree is said to be full binary tree if each of its node has either
two children or no child at all.
Every level is completely filledup. Number of node at any level i in a
full binary tree is given by 2𝑖 .

2. Complete Binary Tree


A complete binary tree is defined as a binary tree where
All leaf nodes are on level n or n-1 Levels are filled from left to right.
heap is an example of complete binary tree

3. Skewed Binary Tree


Skewed binary tree could be skewed to the left or it could be skewed to
the right.
In a left skewed binary tree, most of the nodes have the left child
without corresponding right child.
Binary search tree could be an examples of a skewed binary tree.

By Nitin Sir
109 | R K D E M Y

4. Strictly Binary Tree


If every non-terminal node in a binary tree consists of non-empty left
subtree and right subtree, then such a tree is called strictly binary tree.
In other words, a node will have either two children or no child at all.

Binary Tree Traversal


• Most of the tree operations require traversing a tree in a particular
order.
• Traversing a tree is a process of visiting every node of the tree and
exactly once.
• For example, to traverse a tree, one may visit the root first, then the
left subtree and finally traverse the right subtree.
• If we impose the restriction that left subtree is visited before the right
subtree then three different combination of visiting the root,
traversing left subtree, traversing right subtree is possible.
1. Visit the root, traverse, left subtree, traverse right subtree.
2. Traverse left subtree, visit the root, traverse right subtree.
3. Traverse left subtree, traverse right subtree, visit the root.
These three techniques of traversal are known as preorder, inorder and
postorder traversal of a binary tree.

Preorder traversal (recursive)

• First Visit the root


• Next, Traverse left subtree
• At last, traverse the right subtree.

void preorder(node* T ) /* address of root node is passed in T */


{
if(T!=NULL)
{
printf(“\n%d",T→data);

By Nitin Sir
110 | R K D E M Y

preorder (T→ left);


preorder(T→ right ):
}

Inorder traversal (Recursive)


• Firstly, traverse the left subtree in inorder
• Next, visit the root node
• At last, traverse the right subtree in inorder.

void inorder(node*T) /* address of the node is passed in T */

if (T!=NULL)

inorder (T→left);

printf(‘\n%, T→data);

inorder (T→ right);

Postorder Traversal (recursive)

• Firstly, traverse the left subtree in postorder


• Next, traverse the right subtree in postorder
• At last, visit the root node.

void postorder(node*T) /* address of the root node passed in T*/

if(T!= NULL)

By Nitin Sir
111 | R K D E M Y

postorder(T→left);

postorder (T→right);

print (“\n%d”,T→data);

1. Perform inorder, preorder and postorder traversal of the following


binary tree

Preorder sequence : A B C D E F G H I J

Inorder sequence : D C E B G F A I H J

Postorder sequence : D E C G F B I J H A

2. For the given binary tree, perform inorder, preorder and postorder
traversal.

By Nitin Sir
112 | R K D E M Y

Postorder sequence : A B D G K H L M C E

Inorder sequence : K G D L H M A E C

Preorder sequence : K G L M H D B E C A

By Nitin Sir
113 | R K D E M Y

Construction of binary tree from preorder and inorder traversal sequence

Preorder A B D G C E H I F
Inorder D G B A H E I C F

Step 1 :
A

DGB HEICF
Step 2 :
A

B C

DG F
HE
I

Step 3 :

C
B

D F
E

F H I

By Nitin Sir
114 | R K D E M Y

Binary Search Tree (BST)

A binary search tree is a binary tree, which is either empty or in which each
node contains a key that satisfies the following conditions

1. All keys are distinct.


2. For every node, X in the tree, the values of all the keys in its left subtree
are similar than the key value in X.
3. For every node, X in the tree, the of all the keys in its right subtree are
larger than the key value in X.

The basic operations that can be performed on a binary search tree data
structure, are the following −

• Find − Searches an element in a tree.


• Insert − Inserts an element in a tree/create a tree.
• Delete- Delete an element in a tree.
• FindMin -Find minimum element in a tree
• Findmax – find maximum element in a tree
• Create – create BST tree.

Find Operation
Whenever an element is to be searched, start searching from the root node,
then if the data is less than the key value, search for the element in the left
subtree. Otherwise, search for the element in the right subtree.

Recursive
BSTnode * Find(BSTnode *root, int x)
{

if (root == NULL )
{
return(null);
}

By Nitin Sir
115 | R K D E M Y

if(root→data == x)
return root;
if (root->key < key)
return search(root→right, x);
else
return search(root→left, x);
}

Non recursive
BSTnode * Find(BSTnode *root, int x)
{
while(root != null)
{
If(x==root→data)
return (root);
if(x>root→data)
root=root->right;
else
root=root→left;
}
return(NULL);
}

Insert Operation

The very first insertion creates the tree. Afterwards, whenever an element is
to be inserted, first locate its proper location. Start searching from the root
node, then if the data is less than the key value, search for the empty location
in the left subtree and insert the data. Otherwise, search for the empty
location in the right subtree and insert the data.

By Nitin Sir
116 | R K D E M Y

BSTnode* insert(BSTnode* T, int X)


{
/* If the tree is empty, return a new node */
if (T== NULL)
{
T=(BSTnode *)malloc(sizeof(BSTnode));

T->data = x;

T->left = T->right = NULL;

return temp;

}
/* Otherwise, recur down the tree */
if (X <T->data)
T->left = insert(T->left, X);
else if (X> T->key)
T->right = insert(T->right, key);
return (T);
}

Delete Operation
1. A Leaf node
2. A node with one child.
3. A node with two child.

By Nitin Sir
117 | R K D E M Y

1. A Leaf node

If node is a leaf node, it can be deleted immediately by setting the


corresponding parent pointer to NULL.

2. A node with one child.

When node to be deleted has one child, it can be deleted easily.

If node q is to be deleted and it is right child of its parent node p. the only
child of q will become the right child of p after deletion of q.

Similarly if a node q is to be deleted and it is left child of its parent node p,


only child of q will become the left child of p after deletion.

By Nitin Sir
118 | R K D E M Y

3. A node with two child.


When node to be a deleted has two child is to replace the data of this node with smallest
data of right subtree. Smallest data can be either leaf node or a node with degree 1.

BSTnode* delete(BSTnode *root, int x)


{
//searching for the item to be deleted
if(root==NULL)
{
return NULL;
}
if(x>root->data)
{
root->right = delete(root->right, x);
}
if(x<root->data)
{
root->left = delete(root->left, x);
}
//No Children
if(root->left ==NULL && root->right ==NULL)
{
free(root);
return NULL;
}

//One Child
if(root->left ==NULL || root->right ==NULL)
{

By Nitin Sir
119 | R K D E M Y

BSTnode *temp;
if(root->left ==NULL)
temp = root->right;
else
temp = root->left;
free(root);
return temp;
}

//Two Children
else
{

BSTnode *temp = find_min(root->right);


root->data = temp->data;
root->right = delete(root->right, temp->data);
}
}
return root;
}

BSTnode* find_min(BSTnode *root)


{
While(root->left != NULL)
{
root=root->left; // left most element will be minimum
}
return root;
}

BSTnode* find_max(BSTnode *root)


{
While(root->right != NULL)
{
root=root->right; // left most element will be minimum
}
return root;
}

By Nitin Sir
120 | R K D E M Y

Stepwise construction of Binary search tree for following elements:

30,100,90,15,2,25,36,72,78,10

By Nitin Sir
121 | R K D E M Y

Threaded Binary Tree

In linked representation of tree, there are more number When a binary tree
is represented using linked list representation.

If any node is not having a child we use a NULL pointer. These special
pointers are threaded and the binary tree having such pointers is called a
threaded binary tree.

Thread in a binary tree is represented by a dotted line

This NULL pointer does not play any role except indicating there is no child.

There are two types of threaded binary trees.


Single Threaded: Where a NULL right pointers is made to point to the
inorder successor (if successor exists)

Double Threaded: Where both left and right NULL pointers are made to
point to inorder predecessor and inorder successor respectively. The
predecessor threads are useful for reverse inorder traversal and postorder
traversal.

The threads are also useful for fast accessing ancestors of a node.

Following diagram shows an example Single Threaded Binary Tree. The


dotted lines represent threads.

Why do we need Threaded Binary Tree?

• Binary trees have a lot of wasted space: the leaf nodes each have 2 null
pointers. We can use these pointers to help us in inorder traversals.
• Threaded binary tree makes the tree traversal faster since we do not
need stack or recursion for traversal

By Nitin Sir
122 | R K D E M Y

Huffman Coding

Huffman coding is a lossless data encoding algorithm

A text message can be converted into a sequence of 0’s and 1’s by replacing
each character of the message with its code.

It uses variable length encoding where variable length codes are assigned to
all the characters depending on how frequently they occur in the given text.

The character which occurs most frequently gets the smallest code and the
character which occurs least frequently gets the largest code.

Huffman’s algorithm

1. Each character is converted into a single node tree.


2. Each node is labelled by its frequency.
3. Arrange all the nodes in the increasing order of frequency value
contained in the nodes.
4. Select first two nodes having minimum frequency.
5. Combine these two nodes into one weight of combined tree= sum of
weight of two nodes.
6. Keep repeating Step-04 and Step-05 until all the nodes form a single
tree.

A file contains the following characters with the frequencies as shown. If


Huffman coding is used for data compression, determine-

1. Huffman code for each character


2. Average code length
3. Length of Huffman encoded message (in bits)

Characters Frequencies

A 10

E 15

I 12

O 3

U 4

By Nitin Sir
123 | R K D E M Y

S 13

t 1

Solution-

First let us construct the Huffman tree using the steps we have learnt above-

Step-01:

Step-02:

Step-03:

Step-04:

By Nitin Sir
124 | R K D E M Y

Step-05:

By Nitin Sir
125 | R K D E M Y

Step-06:

Step 7

By Nitin Sir
126 | R K D E M Y

By Nitin Sir
127 | R K D E M Y

After we have constructed the Huffman tree, we will assign weights to all the edges. Let us assign
weight ‘0’ to the left edges and weight ‘1’ to the right edges

1. Huffman code for the characters-

We will traverse the Huffman tree from the root node to all the leaf nodes
one by one and and will write the Huffman code for all the characters-

• a = 111
• e = 10
• i = 00
• o = 11001
• u = 1101
• s = 01
• t = 11000

2. Average code length-

Average code length

By Nitin Sir
128 | R K D E M Y

= ∑ ( frequencyi x code lengthi ) / ∑ ( frequencyi )

= { (10 x 3) + (15 x 2) + (12 x 2) + (3 x 5) + (4 x 4) + (13 x 2) + (1 x 5) } / (10


+ 15 + 12 + 3 + 4 + 13 + 1)

= 2.52

Length of Huffman encoded message-

Total number of bits in Huffman encoded message

= Total number of characters in the message x Average code length per


character

= 58 x 2.52

= 146.16

AVL TREE
Adelson, Velski & Landis, AVL trees are height balancing binary search
tree. AVL tree checks the height of the left and the right sub-trees and
assures that the difference is not more than 1. This difference is called the
Balance Factor.

BalanceFactor=height(leftsutree)−height(right sutree)

If the difference in the height of left and right sub-trees is more than 1, the
tree is balanced using some rotation techniques.

AVL Rotations

To balance itself, an AVL tree may perform the following four kinds of
rotations −

• Left rotation
• Right rotation
• Left-Right rotation
• Right-Left rotation

By Nitin Sir
129 | R K D E M Y

The first two rotations are single rotations and the next two rotations are
double rotations. To have an unbalanced tree, we at least need a tree of
height 2. With this simple tree, let's understand them one by one.

Left Rotation

If a tree becomes unbalanced, when a node is inserted into the right subtree
of the right subtree, then we perform a single left rotation −

In our example, node A has become unbalanced as a node is inserted in the


right subtree of A's right subtree. We per form the left rotation by making
A the left-subtree of B.

Right Rotation

AVL tree may become unbalanced, if a node is inserted in the left subtree of
the left subtree. The tree then needs a right rotation.

As depicted, the unbalanced node becomes the right child of its left child by performing a
right rotation.

Left-Right Rotation
State Action

By Nitin Sir
130 | R K D E M Y

A node has been inserted into the right subtree of the left subtree.
This makes C an unbalanced node. These scenarios cause AVL tree
to perform left-right rotation.

We first perform the left rotation on the left subtree of C. This


makes A, the left subtree of B.

Node C is still unbalanced, however now, it is because of the left-


subtree of the left-subtree.

We shall now right-rotate the tree, making B the new root node of
this subtree. C now becomes the right subtree of its own left
subtree.

The tree is now balanced.

Right-Left Rotation

The second type of double rotation is Right-Left Rotation. It is a combination of right


rotation followed by left rotation.

By Nitin Sir
131 | R K D E M Y

State Action

A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.

First, we perform the right rotation along C node, making C the


right subtree of its own left subtree B. Now, B becomes the right
subtree of A.

Node A is still unbalanced because of the right subtree of its right


subtree and requires a left rotation.

A left rotation is performed by making B the new root node of the


subtree. A becomes the left subtree of its right subtree B.

The tree is now balanced.

By Nitin Sir
132 | R K D E M Y

Expression tree

When expression is represented through a tree, it is known as an expression


tree.

The leaves of an expression tree are operands, such as constants or variables


and all internal nodes contains operations.

The preorder traversal produces the prefix representation, the in-order


traversal produces the infix representation, and the post-order traversal
produces the postfix representation of the expression.

Construct binary tree for the following expression

A+B*C+D*E

Construct binary tree for following expression.

(A+B) (B*C) + D/E

By Nitin Sir
133 | R K D E M Y

B-Trees

B-Tree is a self-balanced search tree in which every node contains multiple


keys and has more than two children

The B-tree is a generalization of a binary search tree in that a node can have
more than two children.

When large volume of data is handled, the search tree can not
accommodated in primary, b tree primarily meant for secondary storage.

B-Tree is a M-way tree. And M-way tree can have maximum of M children.

Properties of B-Tree

1. All leaf nodes must be at same level.

By Nitin Sir
134 | R K D E M Y

2. All nodes except root must have at least [m/2]-1 keys and maximum
of m-1 keys.
3. All non leaf nodes except root (i.e. all internal nodes) must have at
least m/2 children.
4. If the root node is a non leaf node, then it must have atleast 2 children.
5. A non leaf node with n-1 keys must have n number of children.
6. All the key values in a node must be in Ascending Order.

By Nitin Sir
135 | R K D E M Y

GRAPHS
A graph G is a set of vertices (V) and set of edges (E)

G=(V,E)

V(G)=Vertices of graph G

E(G)=Edges of graph G

V(𝐺1 )={A,B,C,D,E,F}

Types of Graph

1. Undirected Graph
A graph containing unordered pair of vertices is called an undirected
graph.
In an undirected graph, pair of vertices (1,0) and (0,1)represent the
same edge.

2. Directed Graph
A graph containing ordered pair of vertices is called a direct graph.

If an edge is represented using a pair of vertices (1,0) then the edge is


said to be directed from 1 to 0
1 is called predecessor of 0 and 0 is successor

By Nitin Sir
136 | R K D E M Y

3. Complete Graph
An undirected graph, in which every vertex has an edge to all other
vertices is called a complete graph.

4. Weighted Graph
A weighted graph is a graph in which edges are assigned some value.
Most of the physical situation shown using weighted graph.
A weighted graph is a graph in which edges are assigned some value.

The weight will denote the distance between two connected cities
using highway

By Nitin Sir
137 | R K D E M Y

Cycle

A cycle is a simple path that begins and ends at the same vertex.

Cost : The cost of a graph is the sum of the cost of the edges in the weighted
graph.

TREE

Tree is connected graph without any cycle,

Degree of Vertex:-

The total number of edges linked to a vertex is called its degree.

The indegree of a vertex is the total number of edges coming to that


node .

The outdegree of a node is the total number of edges going out from
that node.

A vertex, which has only outgoing edges and no incoming edges, is


called source

By Nitin Sir
138 | R K D E M Y

Spanning tree

A spanning tree of graph G=(V,E) is subgraph of G having all vertices of


G and no cycle in it.

A spanning tree of a group G=(V,E) is called a minimal cost spanning


tree or simply the minimal spanning tree of G if its cost is minimum
If graph G is not connected then there is no spanning trees

Minimal Spanning Tree

The cost of the spanning tree is the sum of the weights of all the edges in the
tree. There can be many spanning trees.

Minimum spanning tree is the spanning tree where the cost is minimum
among all the spanning trees. There also can be many minimum spanning
trees.

By Nitin Sir
139 | R K D E M Y

Representation of graphs

Graph can be represented using two ways

1. Adjacency matrix
A two dimensional matrix can be used to store a graph.
A graph is represented using a square matrix.

If graph G=(V,E) where vertices V={0,1,2,3…} can be represented using


a two dimensional array.
e.g.
int adj[20][20];
can be used to store a graph with 20 vertices.

If adj[i][j]=1, indicates presence of edge between two vertices i and j.


adj[i][j]=0, indicates absence of edge between two vertices i and j.

Adjacency matrix of an undirected graph is always a symmetric matrix


Adjacency matrix of a directed graph is never symmetric

By Nitin Sir
140 | R K D E M Y

Adjacency List

A graph can be represented using a linked list For each vertex a list of
adjacent vertices is maintained using a linked list.

The adjacency list representation maintains each node of the graph


and a link to the nodes that are adjacent to this node.

When we traverse all the adjacent nodes, we set the next pointer to
null at the end of the list.

By Nitin Sir
141 | R K D E M Y

Traversal of graph

Graph traversal means visiting each node of graph exactly once.

We need standard techniques to keep things uniform.

Different techniques used for graph traversal are

1. Depth First Search(DFS)


2. Breadth First Search(BFS)

Depth First Search(DFS)

• This algorithm traverses the tree depth-wise.


• It is like preorder traversal of a tree.
• In this method all vertices are stored in stack and each vertex of graph
is visited or explored once.
• The newest vertex(added last) in the stack is explored first.
• Traversal can start from any vertex say v.
• V is visited then all vertices adjacent to v are visited recursively using
dfs.
• Since graph can have cycle, we must avoid revisiting a node.
• When we visit vertex v, we marks it visited, a node that has already
been marked as visited should not be selected for traversal.

By Nitin Sir
142 | R K D E M Y

Algorithm

1. Initialize all the vertices.


2. Initialize array of visited[ ] to false (0).
3. Push starting vertex onto stack.
4. Repeat steps 5 and 6 until stack is empty.
5. Pop the top vertex from stack.
6. Push onto stack all the neighbors of popped vertex
7. End.

Depth First Search (DFS) Program in C


#include<stdio.h>
#include<conio.h>
void DFS(int);
int G[10][10];
int visited[10],n; //n is no of vertices and graph is sorted in array
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)

By Nitin Sir
143 | R K D E M Y

{
scanf("%d",&G[i][j]);
}
}
//visited is initialized to zero
for(i=0;i<n;i++)
{
visited[i]=0;
}
DFS(0);
}
void DFS(int i)
{
int j;
printf("%d",i);
visited[i]=1;
for(j=0;j<n;j++)
{
if(!visited[j] && G[i][j]==1)
{
DFS(j);
}
}
}

By Nitin Sir
144 | R K D E M Y

Breadth First Search(BFS)

• It is another popular approach used for visiting the vertices of a graph.

• This method starts from a give 𝑉0 . 𝑉0 is marketed as visited.

• All vertices adjacent to 𝑉0 are visited next.

• The algorithm for BFS has to maintain a list of vertices which have
been visited but not explored for adjacent vertices.
• The vertices which have been visited but not explored for adjacent
vertices can be stored in queue.

• Initially the queue contains the starting vertex.

• In every iteration, a vertex is removed from the queue and its adjacent
vertices which are not visited as yet are added to the queue.

• The algorithm terminates when the queue become empty.

By Nitin Sir
145 | R K D E M Y

Algorithm
1. Initialize all the vertex.
2. Initialize array of visited [ ] to false (0)
3. Enqueue starting vertex in queue.
4. Mark it as visited [ ] to true (1)
5. Dequeue from queue.
6. Add to rear of queue all neighbors of deleted node that are not
visited.
7. If queue is not empty go to step5.
8. End.

#include<stdio.h>
#include<conio.h>
typedef struct Queue
{
Int data[max];
Int F,R;
}Queue;
Void enqueue(Queue *q,int x);
Void Init(Queue *q);
int dequeue(Queue *q);
int empty((Queue *q);
void BFS(int);

By Nitin Sir
146 | R K D E M Y

int G[10][10];
int visited[10],n; //n is no of vertices and graph is sorted in array
void main()
{
int i,j,v;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&G[i][j]);
}
}
//visited is initialized to zero
for(i=0;i<n;i++)
{
visited[i]=0;
}
Printf(“Enter the starting vertex\n”);
Scanf(“%d”,&v);
BFS(v);
getch();
}
Void BFS(int v)
{
Queue q;
Init(&q);
Enqueue(&q, v);
printf(“%d”, v);
visited [v]=1;
while(!empty(&q))
{
V=dequeue(&q);
For ( i=0 ; i<n ; i++)

By Nitin Sir
147 | R K D E M Y

{
If(visited[i]==0 && G[V][i]==1)
{
enqueue( &q, i);
visited[i]=1;
printf(“%d”,i);
}
}
}
}

Important questions
What is graph explain methods to represent graph [May, DEC-18 5M]

Explain Graph Traversal Techniques [DEC17,MAY-18 10M]

Give c function for BFS traversal in a graph? explain with example?


[10M DEC -18]

Define minimum spanning tree ? list the technique to compute


minimum spanning tree [3M MAY-18]

Explain BFS and DFS algorithm with example [10M MAY-18]

Explain kruskal’s algorithm with example [10M May-18]

Write a short note on prims algorithm and Dijkstra algorithm [10M


May-18]

Define graph? List the types of graph with example? [3M DEC-18]

What is minimal spanning tree ? Draw MST using kruskal’s and prims
algorithm and find out cost. [10M DEC-18]

Explain BFS and DFS algorithm with example [10M DEC-17]

By Nitin Sir
148 | R K D E M Y

Sorting & Searching


What is Sorting

Sorting is a process of ordering a list of elements in either ascending or


descending order.

Sorting can be divided into two categories:

1. Internal sorting
2. External sorting

1. Internal sorting
Internal sorting takes place in the main memory of the computer.

Internal sorting can take advantage of the random access nature of


the main memory.

2. External sorting
External sorting is carried on secondary storage.

External sorting becomes a necessity if the number of elements


to be sorted is too large to fit in main memory.

Sorting Efficiency

In order to find the amount of time required to sort a list of n elements


by a particular method, we must find the number of comparisons
required to sort.

1. Best case
2. Worst case
3. Average case
Most of the primitive sorting algorithms like bubble sort, selection sort and
insertion sort are not suited for sorting a large files.

These algorithms have a timing requirement of 𝑂(𝑛2 ).

On the contrary, these sorting algorithms require hardly any additional


memory space for sorting.

Advance sorting algorithms like quick sort, merge sort and heap sort have a
timing requirement of 𝑂(𝑛 𝑙𝑜𝑔𝑛).

By Nitin Sir
149 | R K D E M Y

Bubble Sort
Bubble sort is one of the simplest and the most popular sorting method.

The basic idea behind bubble sort is as a bubble rises up in water, the
smallest element goes to beginning.

Original array with n=6 5 9 6 2 8 1

First pass i=1

j=0 5 9 6 2 8 1

j=1 5 9 6 2 8 1

j=2 5 6 9 2 8 1

j=3 5 6 2 9 8 1

j=4 5 6 2 8 9 1

Second pass i=2

j=0 5 6 2 8 1 9

`j = 1 5 6 2 8 1 9

j=2 5 2 6 8 1 9

j=3 5 2 6 8 1 9

Third pass i=3

j=0 5 2 6 1 8 9

j=1 2 5 6 1 8 9

j=2 2 5 6 1 8 9

Fourth pass i=4

j=0 2 5 1 6 8 9

By Nitin Sir
150 | R K D E M Y

j=1 2 5 1 6 8 9

Fifth pass i= 5

j=0 2 1 5 6 8 9

Sorted array a[ ] => 1 2 5 6 8 9

Program for sorting an integer array using bubble sort.


#include <conio.h>
#include<stdio.h>
void bubble_sort(int[],int);
void main()
{
int a[30],n,i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
{
scanf (“%d”,&a[i]);
}
bubble_sort(a,n);
printf(“\nSorted array is ;”);
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}

By Nitin Sir
151 | R K D E M Y

getch();
}
void bubble_sort(int a[ ],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a(j);
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

Selection Sort
Selection sort is very simple sorting method.
5 9 1 11 2 4 Original array

1 9 5 11 2 4 After first pass

1 2 5 11 9 4 After second pass

1 2 4 11 9 5 After third pass

1 2 4 5 9 11 After forth pass

By Nitin Sir
152 | R K D E M Y

1 2 4 5 9 11 After fifth pass

Write a program to sort number in ascending order


using selection sort.
#include <conio.h>
#include<stdio.h>
void selection_sort(int[ ],int);
void main()
{
int a[50],n,i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
{
scanf (“%d”,&a[i]);
}
selection_sort(a,n);
printf(“\n sorted elements are :”);
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
getch();
}
void selection_sort(int a[],int n)
{
int i,j,k,temp;
for(i=0;i<n-i;i++)

By Nitin Sir
153 | R K D E M Y

{
k=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[k])
{
k=j;
}
}
if(k!=i)
{
temp=a[i];
a[i]=a[k];
a[k]=temp;
}
}
Insertion Sort
An element can always be placed at a right place in sorted list of element
Insertion sort is based on the principle of inserting the element at its
correct place in a previously sorted list. I can be varied 1 to n-1 to sort the
entire array.

By Nitin Sir
154 | R K D E M Y

Write a program to sort number in ascending order


using insertion sort.
#include <conio.h>
#include<stdio.h>
void insertion_sort(int[ ],int);
void main()
{
int a[50],n,i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
scanf (“%d”,&a[i]);
insertion_sort(a,n);
printf(“\n sorted elements are :”);
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}

By Nitin Sir
155 | R K D E M Y

getch();
}
void insertion_sort(int a[], int n)
{
int I, j, temp;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i-1; j>=0 && a[j]>temp; j--)
{
a[j+1]=a[j];
}
a[j+1]=Temp;
}
}

Quick Sort

Quick sort is the fastes internal sorting algorithm with the time complexity=
O(n log n ).

The basic algorithm to sort an array a [] of n elements can be described


recursively as follows

1. Pick any element V in a[]. This is called pivot.


2. Rearrange elements of the xi < V left of V.
3. If the place of the V after re-arrangement is j, all elements with value
less than V, appear in a[0],a[1]…a[j-1] and all those with value grater
than V appear in a[j+1]…a[n-1].

By Nitin Sir
156 | R K D E M Y

void Quick_Sort(int a[], int l, int u)


{
int j;
if(l<u)
{
J=partition(a,l,u);
Quick_sort(a,l,j-1);
Quick_sort(a,j+1,u);
}
}
Int partition (int a[], int l, int u)
{
int v,l,j,temp;
V=a[l];
i=l;

By Nitin Sir
157 | R K D E M Y

j=u+1;
do
{
do
{
i++;
}while(a[i]<v && i<=u);
do
{
j--;
}while(a[j]>v);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return (j);
}

Write a program to sort number in ascending order


using Quick sort.
#include <conio.h>
#include<stdio.h>

By Nitin Sir
158 | R K D E M Y

void Quick_sort(int[ ],int);


void main()
{
int a[50],n, i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
scanf (“%d”,&a[i]);
Quick_sort(a,0,n);
printf(“\n sorted elements are :”);
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
getch();
}

Merge sort
Merge sort runs in O(N Log N ) running time. It is a very efficient sorting
algorithm with near optimal number of comparisons
Basic operation in merge sort is that of merging of two sorted list into one
sorted list. Merging operation has a liner time complex
Advantages and Disadvantages of Merge sort:
Advantages
1. It has a timing complexity of O(n log n).
2. It can be used both for internal as well as external sorting.
3. It is a stable sorting algorithm.

By Nitin Sir
159 | R K D E M Y

Disadvantages

1. It requires an additional memory for storing of merged data during


merging phase.
2. It can take advantage of partially sorted nature of data. Number of
passes are fixed.

Void merge_sort(int a[], int I, int j)


{
Int k;
If(i<j)
{
k=(i+j)2;
Merge_sort(a,i,k);
Merge_sort(a,k+1,j);
Merge(a,i,k,j);
}
}
Void merge( int a[], int l, int m, int u)
{
Int c[20];
int i,j,k;
i=l;
j=m+1;
k=0;
while(i<=m && j<=u)
{

By Nitin Sir
160 | R K D E M Y

If(a[i]<a[j])
{
c[k]=a[i];
k++; i++;
}
else
{
c[k]=a[j];
k++; j++;
}
}
while (i<=m)
{
c[k]=a[i];
k++; i++;
}
while(j<=u)
{
c[k]=a[j];
k++; j++;
}
for(i=l,j=0;i<=u;i++,j++)
{
a[i]=c[j];
}
}

By Nitin Sir
161 | R K D E M Y

By Nitin Sir
162 | R K D E M Y

Radix sort
Radix sort is generalization of bucket sort. To sort decimal numbers, where
the redix or base is 10, we need 10 buckets . These buckets are numbered
0,1,2,3,4,5,6,7,8,9. Sorting is done in passes
Number of passes required to sort using shell sort is equal to number of
digits in the largest number in the list

Range Passes
0to 99 2 passes
0to999 3 passes
0to9999 4 passes

In the first pass, number are sorted on least significant digit. Numbers with
the same least significant digit are sorted in the same bucket

• In the 2nd pass, numbers are sorted on the second least significant
digit.

• At the end of every pass, numbers in buckets are merged to produce a


common list.

• Number of passes depends on the range of numbers being sorted.

• The following example shows the action of radix sort.

By Nitin Sir
163 | R K D E M Y

By Nitin Sir
164 | R K D E M Y

Heap sort
Heap sort is one of the sorting algorithms used to arrange a list of elements
in order.

Heapsort algorithm uses one of the tree concepts called Heap Tree.

In this sorting algorithm, we use Max Heap to arrange list of elements in


Descending order and Min Heap to arrange list elements in Ascending order.

Step by Step Process

The Heap sort algorithm to arrange a list of elements in ascending order is


performed using following steps...

Step 1 - Construct a Binary Tree with given list of Elements.

Step 2 - Transform the Binary Tree into Min Heap.

Step 3 - Delete the root element from Min Heap using Heapify method.

Step 4 - Put the deleted element into the Sorted list.

Step 5 - Repeat the same until Min Heap becomes empty.

Step 6 - Display the sorted list.

By Nitin Sir
165 | R K D E M Y

By Nitin Sir
166 | R K D E M Y

By Nitin Sir
167 | R K D E M Y

Searching
Searching is a technique of finding an element in a given list
of elements
Searching technique should be able to locate the element to
be searched as quickly as possible.
The complexity of any searching algorithm depends on
number of comparisons required to find the element.
Performance of searching algorithm can be found by
counting the number of comparisons in order to find the
given element.

Sequential search (linear search):


In sequential search elements are examined sequentially
starting from the first element.
The process of searching terminates when the list is
exhausted or a comparison result in success.
Algorithm for searching an element ‘key’ in an array ‘a[]’
having elements:
Int sequential( int a[], int key, int n)
{
int i=0’
While (i<n)
{

By Nitin Sir
168 | R K D E M Y

if(a[i]==key)
{
return (i);
}
i++;
}
return (-1);
}
Write a program for sequential search
#include <conio.h>
#include<stdio.h>
void sequential_search(int[ ],int);
void main()
{
int a[50],n, i;
printf(“\nEnter no of elements :”);
scanf(“%d”,&n);
printf(“\nEnter array elements :”);
for(i=0;i<n;i++)
scanf (“%d”,&a[i]);
printf(“Element to be search \n”);
scanf(“%d”, &key);
if(i==-1)

By Nitin Sir
169 | R K D E M Y

{
Printf(“Not found \n”);
}
Else
{
Printf(“Found at location %d”, i+1);
}
getch();
}

Binary Search

Linear search is not applicable when data is on large volume,

Binary search exhibits much better timing behavior in case of large volume
of data.

Algorithm

Binary search is implemented using following steps...

• Step 1 - Read the search element from the user.


• Step 2 - Find the middle element in the sorted list.
• Step 3 - Compare the search element with the middle element in the
sorted list.
• Step 4 - If both are matched, then display "Given element is found!!!"
and terminate the function.
• Step 5 - If both are not matched, then check whether the search
element is smaller or larger than the middle element.
• Step 6 - If the search element is smaller than middle element, repeat
steps 2, 3, 4 and 5 for the left sublist of the middle element.
• Step 7 - If the search element is larger than middle element, repeat
steps 2, 3, 4 and 5 for the right sublist of the middle element.
• Step 8 - Repeat the same process until we find the search element in
the list or until sublist contains only one element.

By Nitin Sir
170 | R K D E M Y

• Step 9 - If that element also doesn't match with the search


element, then display "Element is not found in the list!!!" and terminate
the function.

int bin_Search( int a[], int key, int n)


{
int i,j, c;
i=0;
j=n;
c=(i+j)/2;
While (key==a[c])
{
If(key <a[c])
{
j=c-1;
}
else
{
i=c+1;
}
c=(i+j)/2;
}

By Nitin Sir
171 | R K D E M Y

If(i<=j)
Return c;
Return (-1);
return (i);
}
i++;
}
return (-1);
}
What is Hashing
Hashing is a technique that is used to uniquely identify a specific object from a group of similar
objects. Some examples of how hashing is used in our lives include:

• In universities, each student is assigned a unique roll number that can be used to
retrieve information about them.
• In libraries, each book is assigned a unique number that can be used to determine
information about the book, such as its exact position in the library or the users it has
been issued to etc.

In both these examples the students and books were hashed to a unique number.

Assume that you have an object and you want to assign a key to it to make searching easy. To
store the key/value pair, you can use a simple array like a data structure where keys (integers)
can be used directly as an index to store values. However, in cases where the keys are large and
cannot be used directly as an index, you should use hashing.

In hashing, large keys are converted into small keys by using hash functions.

The values are then stored in a data structure called hash table.

The idea of hashing is to distribute entries (key/value pairs) uniformly across an array.

Each element is assigned a key (converted key). By using that key you can access the element
in O(1) time. Using the key, the algorithm (hash function) computes an index that suggests
where an entry can be found or inserted.

By Nitin Sir
172 | R K D E M Y

Hashing is implemented in two steps:

1. An element is converted into an integer by using a hash function. This element can be
used as an index to store the original element, which falls into the hash table.
2. The element is stored in the hash table where it can be quickly retrieved using hashed
key.

hash = hashfunc(key)
index = hash % array_size

In this method, the hash is independent of the array size and it is then reduced to an index (a
number between 0 and array_size − 1) by using the modulo operator (%).

• Suppose we have integer items {26, 70, 18, 31, 54, 93}. One common method of
determining a hash key is the division method of hashing and the formula is :
Hash Key = Key Value % Number of Slots in the Table

• Division method or reminder method takes an item and divides it by the table size and
returns the remainder as its hash value.
Data Item Value % No. of Slots Hash Value
26 26 % 10 = 6 6
70 70 % 10 = 0 0
18 18 % 10 = 8 8
31 31 % 10 = 1 1
54 54 % 10 = 4 4
93 93 % 10 = 3 3

Hash function
To achieve a good hashing mechanism, It is important to have a good hash function with the
following basic requirements:

1. Easy to compute: It should be easy to compute and must not become an algorithm in
itself.
2. Uniform distribution: It should provide a uniform distribution across the hash table and
should not result in clustering.
3. Less collisions: Collisions occur when pairs of elements are mapped to the same hash
value. These should be avoided.

Note: Irrespective of how good a hash function is, collisions are bound to occur.
Therefore, to maintain the performance of a hash table, it is important to manage
collisions through various collision resolution techniques.

Need for a good hash function

The hash function will compute the same index for all the strings and the strings will be stored
in the hash table in the following format. As the index of all the strings is the same, you can
create a list on that index and insert all the strings in that list.

Hash table
A hash table is a data structure that is used to store keys/value pairs. It uses a hash function to

By Nitin Sir
173 | R K D E M Y

compute an index into an array in which an element will be inserted or searched. By using a
good hash function, hashing can work well. Under reasonable assumptions, the average time
required to search for an element in a hash table is O(1).

Collision resolution techniques

Separate chaining (open hashing)

Separate chaining is one of the most commonly used collision resolution techniques. It is
usually implemented using linked lists. In separate chaining, each element of the hash table is a
linked list. To store an element in the hash table you must insert it into a specific linked list. If
there is any collision (i.e. two different elements have same hash value) then store both the
elements in the same linked list.

The cost of a lookup is that of scanning the entries of the selected linked list for the required
key. If the distribution of the keys is sufficiently uniform, then the average cost of a lookup
depends only on the average number of keys per linked list. For this reason, chained hash tables
remain effective even when the number of table entries (N) is much higher than the number of
slots.

For separate chaining, the worst-case scenario is when all the entries are inserted into the same
linked list. The lookup procedure may have to scan all its entries, so the worst-case cost is
proportional to the number (N) of entries in the table.

Linear probing (open addressing or closed hashing)

In open addressing, instead of in linked lists, all entry records are stored in the array itself.
When a new entry has to be inserted, the hash index of the hashed value is computed and then
the array is examined (starting with the hashed index). If the slot at the hashed index is

By Nitin Sir
174 | R K D E M Y

unoccupied, then the entry record is inserted in slot at the hashed index else it proceeds in some
probe sequence until it finds an unoccupied slot.

The probe sequence is the sequence that is followed while traversing through entries. In
different probe sequences, you can have different intervals between successive entry slots or
probes.

When searching for an entry, the array is scanned in the same sequence until either the target
element is found or an unused slot is found. This indicates that there is no such key in the table.
The name "open addressing" refers to the fact that the location or address of the item is not
determined by its hash value.

Linear probing is when the interval between successive probes is fixed (usually to 1). Let’s
assume that the hashed index for a particular entry is index. The probing sequence for linear
probing will be:

index = index % hashTableSize


index = (index + 1) % hashTableSize
index = (index + 2) % hashTableSize
index = (index + 3) % hashTableSize

Quadratic Probing

Quadratic probing is similar to linear probing and the only difference is the interval between
successive probes or entry slots. Here, when the slot at a hashed index for an entry record is
already occupied, you must start traversing until you find an unoccupied slot. The interval
between slots is computed by adding the successive value of an arbitrary polynomial in the
original hashed index.

Let us assume that the hashed index for an entry is index and at index there is an occupied slot.
The probe sequence will be as follows:

index = index % hashTableSize


index = (index + 12) % hashTableSize
index = (index + 22) % hashTableSize
index = (index + 32) % hashTableSize

By Nitin Sir

You might also like