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

VIT Bhopal University: Practical File Fall 2020-2021

This document contains instructions for a practical file submission for a Data Structures and Algorithms course. It includes 20 experiments covering topics like stacks, queues, linked lists, searching, sorting, trees, and graphs. For each experiment, it lists the algorithm, implementation, and in some cases complexity analysis. It provides contents for quick navigation to different sections.

Uploaded by

Kunal Chandra
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)
839 views

VIT Bhopal University: Practical File Fall 2020-2021

This document contains instructions for a practical file submission for a Data Structures and Algorithms course. It includes 20 experiments covering topics like stacks, queues, linked lists, searching, sorting, trees, and graphs. For each experiment, it lists the algorithm, implementation, and in some cases complexity analysis. It provides contents for quick navigation to different sections.

Uploaded by

Kunal Chandra
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/ 51

VIT Bhopal

University
School of Computing Science & Engineering

Practical File
Fall 2020-2021
Code: CSD-3001

Data Structures & Analysis of


Algorithms
02 NOVEMBER 2020

Submitted By:
Kunal Chandra, 19BCY10028

Submitted To:

Dr. Manas Kumar Mishra


Professor,SCSE
CONTENTS

S. No.
Experiment Page No.

Write the Algorithm and develop a program with menu for various
1 3
operations (push, pop, display, peek) of Stack.

1. Write the Algorithm and develop a program for converting any


given infix expression to the corresponding postfix expression using Stack. 5
2. Write the Algorithm and develop a program for evaluating any
7
given postfix expression using Stack
2
3. Write the Algorithm and develop a program for solving the Tower 10
of Hanoi problem using Stack.

3 Implement a Linear Queue using an array. 10

4 Implement a Circular Queue using an array. 12

5 Implement Singly Linked List and Doubly Linked List operations. 13,15,17

6 Implementation of Stack and Queue using Linked List 18

7 Implementation of Circular Linked list 19

8 21
Write down the algorithm and program for each of the following.
1. Sequential/Linear Search 21
2. Bubble Sort 22
3. Selection Sort.
4. Insertion Sort. 23

9 Write down the Algorithm and Implementation of Binary Search 24


10 Write down the algorithm and Implement the Merge Sort 49

11 Write the Algorithm and Implement the Quick Sort 25

Write the algorithm and Implement the program to find the Optimal order 25
of the parenthesis for the Matrix Chain Multiplication with Minimum cost
12 using Dynamic Programming Strategy.

13 Implement 8 Queen Problem using Backtracking 26

Implement Minimum Spanning Tree using Prim's and Kruskal’s 28


14 Algorithms

Implement Travelling Salesman Problem Solution using Branch and 30


15 Bound

16 Implement Knapsack Problem using Greedy Solution 33

17 Implement BFS and DFS in a given Graph 34

Implement Dijkstra's and Bellman Ford Algorithms for Single Source all
18 destination pair Shortest Path finding in a weighted Graph 36,37,39

19 Implement insertion and deletion in a BST 41,43

Implement String Matching through Naive Algorithm, Robin Karp


Algorithm and KMP Algorithms and compare their run time complexity 45,47
20 for the similar input.

1)

import java.util.*;
class stack //class body starts
{
static Scanner sc=new Scanner(System.in); //Static Input Stream
static int top=-1,n,a[]; // static global variables

void push(int x) //function to insert elements into the stack


{

if(isfull()==true) //check if the stack is full


System.out.println("Stack is overflow");

else
{
a[++top]=x; //inserting the element into the stack
}
}
void pop()
{
if(isEmpty()==true) //checking if stack is empty
System.out.println("Stack is underflow");

else
System.out.println("Popped: "+a[top--]); //popping the topmost
element from the stack
}

void peek()
{
if(isEmpty()==true)
System.out.println("Nothing to peek");

else
System.out.println("Peeking at: "+a[top]);
}

void size() //function to return the size of the stack


{
if(top<0)
System.out.println("Stack is underflow");
else
System.out.println("Size is: "+(top+1));
}

boolean isEmpty() //function to check whether the stack is empty


or not
{
if(top<0)
return true;
else
return false;
}

boolean isfull() //function to check whether the stack is full or


not
{
if(top==n-1)
return true;
else
return false;
}

void show() //function to display all the elements present in the


stack
{
for(int i=0;i<=top;i++)
System.out.println(a[i]+" ");
}

public static void main(String args[]) //Main body starts


{
System.out.println("enter size of the array: ");
n=sc.nextInt(); //taking input the size of the Stack
a=new int[n]; //initializing the stack with the inputted size
stack obj=new stack(); //creating the object of the class
stack
obj.push(10);
obj.push(15);
obj.push(20); //FUNTION CALLING
obj.push(25);
obj.push(30);
obj.push(35);
obj.show();
obj.size();
obj.pop();
obj.peek();
obj.size();
System.out.println("Empty: "+obj.isEmpty());
obj.show();
System.out.println("Full: "+obj.isfull());
} //MAIN BODY ENDS
} //CLASS BODY ENDS

2.1)
//POSTFIX EVALUATION

import java.util.*;
class postfix // CLASS BODY BEGINS
{
static Scanner sc=new Scanner(System.in); //STATIC INPUT STREAM
static int top=-1,n; //STATIC GLOVBAL VARIABLES
static String a[]; //STRING ARRAY

void push(String x) //FUNCTION TO INSERT INPUTTED ELEMENT


{
String res=""; //LOCAL VARIABLE TO STORE THE RESULT RETURENED
BY THE EVALUATE() FUNCTION
if(top==n-1)
System.out.println("Stack is overflow");

else if(x=="+" || x=="*" || x=="-" || x=="/") //CHECKING FOR


OPERATOR
{
a[++top]=x; //INSERTING THE OPERATOR INTO THE STACK
res=evaluate(); //CALLING THE EVALUATION FUNCTION
a[++top]=res; //STORING THE RETURNED VALUE BACK INTO THE
STACK
}

else
a[++top]=x; //INSERTING THE ELEMENT INTO THE STACK
}

String pop() //function to remove the topmost element


{
if(top<0)
return null;

else
return(a[top--]);
}

String evaluate() //FUNCTION TO EVALUATE THE EXPRESSION


{
int r=0;
String op,op1,op2;
op=pop(); //CALLING THE POP FUNCTION TO POP THE TOP VALUE
AND STORING THE OPERATOR
op1=pop(); //STORING THE 2ND OPERAND
op2=pop(); //STORING THE FIRST OPERAND

if(op=="+")
{
r=Integer.parseInt(op2)+Integer.parseInt(op1); //IMPLICIT
STRING TO INTEGER CONVERTION FOR THE PURPOSE OF CALCULATION

}
else if(op=="-")
{
r=Integer.parseInt(op2)-Integer.parseInt(op1);
}

else if(op=="*")
{
r=Integer.parseInt(op2)*Integer.parseInt(op1);

}
else if(op=="/")
{
r=Integer.parseInt(op2)/Integer.parseInt(op1);

}
return (Integer.toString(r)); //AGAIN IMPLICITELY CONVERTING
THE RESULTANT VALUE BACK TO THE STRING TYPE AND RETURNING TO THE STACK
}

void show() //METHOD TO DISPLAY ALL THE ELEMENTS STORED IN THE


STACK
{
for(int i=0;i<=top;i++)
System.out.println(a[i]);
}
public static void main(String args[]) //MAIN BODY STARTS
{
System.out.println("enter size: ");
n=sc.nextInt(); //TAKING THE SIZE OF THE STACK FROM THE USER
a=new String[n]; //INITIALIZING THE ARRAY WITH THE INPUTTED
SIZE

postfix obj=new postfix();

obj.push("2");
obj.push("3");
obj.push("1");
obj.push("*"); //FUNCTIONS CALLING
obj.push("+");
obj.push("9");
obj.push("-");
obj.show();
} //MAIN BODY ENDS
} //CLASS BODY ENDS

2.2)

import java.util.*;
class inf_post // CLASS BODY BEGINS
{
static Scanner sc=new Scanner(System.in); //STATIC INPUT STREAM
static int top=-1,n; //STATIC GLOVBAL VARIABLES
static String a[],p=""; //STRING ARRAY

void push(String x) //FUNCTION TO INSERT INPUTTED ELEMENT


{
String f="",s=""; //LOCAL VARIABLE TO STORE THE RESULT
RETURENED BY THE EVALUATE() FUNCTION
int d=0,b=0;

if(top==n-1)
System.out.println("Stack is overflow");

else if(x.equals("+") || x.equals("*") || x.equals("-") ||


x.equals("/") || x.equals("^") || x.equals("(")) //CHECKING FOR
OPERATOR
{
if(top<0)
a[++top]=x;

else //A+B*C/(E-F)
{
if(x.equals("("))
a[++top]=x;
else
{ //CHECKS THE
PRECEDENCE OF THE INPUT VALUE WITH THE TOP VALUE OF THE STACK
f=pre(x);
d=Integer.parseInt(f);
s=pre(a[top]);
b=Integer.parseInt(s);

if(d==b || d<b) //Same PRECEDENCE


{
if(b==-1)
a[++top]=x;
else
{
String q="";
System.out.print(pop()); //Popping
if(top!=-1)
{
q=a[top];

if(x.equals(q)) //IF INPUT AND TOP


PRECEDENCE IS SAME
{
System.out.print(pop()); //POPPED
THE TOP ELEMENT
a[++top]=x; //PUSHED
THE INPUT ELEMENT
}

}
}
else if(d>b) //INPUT PRECEDENCE IS GREATER
{
a[++top]=x; //PUSHED THE INPUT ELEMENT
}
}
}
}
else if(x.equals(")")) //AS SOON AS CLOSED PARENTHESIS IS
ENCOUNTERED
{
while(!a[top].equals("("))
{
String t=pop();
if(!t.equals("("))
System.out.print(t); //POP ALL THE ELEMENTS UNTIL OPEN
PARANTHESIS
}
}

else
System.out.print(x);

String pop() //function to remove the topmost element


{
if(top<0)
return null;

else
return(a[top--]);
}

String pre(String p) //FUNTION TO RETURN THE PRECEDENCE OF THE


OPERATORS
{
String r="";
if(p.equals("*") || p.equals("/"))
r="2";

else if(p.equals("+") || p.equals("-"))


r="1";

else if(p.equals("^"))
r="3";

else
r="-1";

return(r);
}

public static void main(String args[])


{
System.out.println("Enter infix expression: ");
p=sc.nextLine(); //INPUT EXPRESSION
n=p.length();
a=new String[n]; //INTIALIZING THR ARRAY
String q;
inf_post obj=new inf_post(); //CREATING THE OBJECT

for(int i=0;i<p.length();i++)
{
q="";
q=Character.toString(p.charAt(i)); //CONVERTING THE
CHARACTER TO STRING
obj.push(q); //CALLING THE PUSH FUNCTION AND PASSING THR
EXTRACTED VALUE
}
while(top!=-1) //LOOP TO PRINT THE REMAINING ELEMENTS
{
if(!a[top].equals("("))
System.out.print(a[top--]);
else
top--;
}

}
}

2.3)
import java.util.*;
class hanoi
{
static int n,s=0;

static void move(int s,int d,int h,int n)


{
if(n==1)
{
System.out.println("Moving disk 1 from "+s+" to "+d);
return;
}
move(s,h,d,n-1);
System.out.println("Moving disk "+n+" from "+s+" to "+d);
move(h,d,s,n-1);
}

public static void main(String args[])


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of disk: ");
n=sc.nextInt();
int s=1,h=2,d=3;
move(s,d,h,n);
}
}

3)

import java.util.*;
class Queue
{
static Scanner sc=new Scanner(System.in); //static Scanner class
to take input streams
static int n,rear=-1,front=0,a[]; //global variables

int que(int x) //function to insert an element in the queue if


there is empty space
{
if(rear>=n-1)
return(-1);
else
{
a[++rear]=x; //inserting element in the queue
return(a[rear]);
}
}
void dque() //function to delete the element from the queue
{
if(rear<0)
System.out.println("Empty");
else
System.out.println("Element removed: "+a[front++]); //printing
the deleted element
}
int size() //function to return the size of the queue
{
if(rear<0)
return(-1); //returning -1 if the queue is empty
else
return(rear+1); //returning the present size of the queue
}

void peek()
{
System.out.println("Peeking at: "+a[rear]);
}

void show() //function to display all the elements present in the


queue
{
for(int i=front;i<=rear;i++) //loop to traverse through the
queue
{
System.out.print(a[i]+" ");
}
System.out.println();
}
public static void main(String args[]) //Main method or the Driver
Method
{
System.out.println("enter size: ");
n=sc.nextInt(); //taking input the size of the queue from the
user
a=new int[n]; //initializing the array with that size
Queue obj=new Queue(); //creating the object for method
calling

System.out.println("enter elements: ");

for(int i=0;i<n;i++) //taking input of the queue elements


from the user
obj.que(sc.nextInt()); //calling the que method to insert the
elements

System.out.println(obj.size());
obj.show();
obj.dque(); //METHOD CALLING
obj.peek();
obj.show();
}
}

4)

import java.util.*;
class circular_queue
{
static Scanner sc=new Scanner(System.in); //static Scanner class
to take input streams
static int n,rear=0,front=0,a[]; //global variables

int que(int x) //function to insert an element in the queue if


there is empty space
{
if(rear==front-1 ||(rear>n-1 && front==0))
return(-1);

else if(rear>(n-1) && front!=0)


{
rear=rear%n; //rotating the index
a[rear++]=x; //inserting element in the queue
}
else
a[rear++]=x;
return(a[rear-1]);
}
void dque() //function to delete the element from the queue
{
if(rear==front) //checking if the queue is empty
System.out.println("Empty");
else
{
front=front%n; //rotating the index
System.out.println("Element removed: "+a[front++]);
//printing the deleted element
}
}

int size() //function to return the size of the queue


{
if(rear<0)
return(-1); //returning -1 if the queue is empty
else
return(Math.abs(front-rear)); //returning the present size of
the queue
}

void peek()
{
System.out.println("Peeking at: "+a[rear-1]);
}

void show() //function to display all the elements present in the


queue
{
if(rear>front)
{
for(int i=front;i<rear;i++) //loop to traverse through
elements of the queue from front to the rear
{
System.out.print(a[i]+" ");
}
}
else
{
for(int i=front;i<n;i++) //loop to traverse through the
front till end of the queue,if rear is in the beginning
{
System.out.print(a[i]+" ");
}
for(int i=rear;i<front;i++) //loop to traverse through the
queue
{
System.out.print(a[i]+" ");
}
}
System.out.println();
}
public static void main(String args[]) //Main method or the Driver
Method
{
System.out.println("enter size: ");
n=sc.nextInt(); //taking input the size of the queue from the
user
a=new int[n]; //initializing the array with that size
circular_queue obj=new circular_queue(); //creating the
object for method calling

System.out.println("enter elements: ");

for(int i=0;i<n;i++) //taking input of the queue elements


from the user
obj.que(sc.nextInt()); //calling the que method to insert the
elements

System.out.println(obj.size());
obj.show();
obj.dque(); //METHOD CALLING
obj.peek();
obj.show();
obj.que(7);
obj.show();
}
}

5)

import java.util.*;
class linked
{
static Scanner sc=new Scanner(System.in);
Node head;
public class Node
{
Node next;
int data;
}

public void insert(int d)


{
Node node=new Node();
node.data=d;

if(head==null)
head=node;

else
{
Node n=head;

while(n.next!=null)
{
n=n.next;
}
n.next=node;
}
}

public void insert(int pos,int d)


{
if(pos==0)
insert(d);

else
{
Node node=new Node();
node.data=d;
//node.next=null;
Node n=head;

for(int i=0;i<pos-2;i++)
{
n=n.next;
}
node.next=n.next;
n.next=node;
}
}

void delete(int pos)


{
Node n=head;
Node n1=null;

if(head==null)
System.out.println("nothing to delete: Empty");

else
{
for(int i=0;i<pos-2;i++)
{
n=n.next;

}
n1=n.next;
n.next=n1.next;
System.out.println("deleted element is :"+n1.data);
}
}

public void show()


{
Node n=head;
while(n.next!=null)
{
System.out.println(n.data);
n=n.next;
}
System.out.println(n.data);
}

public static void main(String args[])


{
linked obj=new linked();
obj.insert(4);
obj.insert(5);
obj.insert(6);
obj.insert(7);
obj.insert(4,8);
obj.show();
obj.delete(3);
obj.show();
}
}

5.1)

import java.util.*;
class doubly
{
static Scanner sc=new Scanner(System.in);
static Node head;

static public class Node


{
Node next;
Node prev;
int data;
}

static void insert_end(int d)


{
Node node=new Node();
node.data=d;
if(head==null)
{
node.prev=null;
head=node;
}

else
{
Node n=head;
while(n.next!=null)
{
n=n.next;
}
n.next=node;
node.prev=n;
}
}

static void insert_front(int d)


{
Node node=new Node();
node.data=d;
if(head!=null)
{
node.next=head;
node.prev=null;
head=node;
}
else
head=node;
}

static void insert(int pos,int d)


{
Node node=new Node();
node.data=d;
Node n=head;
for(int i=0;i<pos-2;i++)
{
n=n.next;
}
node.next=n.next;
n.next=node;
node.prev=n;
if (node.next != null)
node.next.prev=node;

static void insert_before(Node a,int d)


{
Node node=new Node();
node.data=d;
if(a.prev==null)
{
node.next=a;
a.prev=node;
node.prev=null;
}
else
{
node.prev=a.prev;
node.next=a;
a.prev.next=node;
a.prev=node;
}

static void insert_after(Node a,int d)


{
Node node=new Node();
node.data=d;
if(a==null)
System.out.println("the given previous node cannot be NULL");

node.next=a.next;
node.prev=a;
a.next=node;
if(node.next.prev!=null)
node.next.prev=node;

static void show()


{
Node n=head;

while(n!=null)
{
System.out.print(n.data+" ");
n=n.next;
}
System.out.println();
}

public static void main(String args[])


{
System.out.println("enter no of nodes:" );
int n=sc.nextInt();
System.out.println("enter nodes: ");
for(int i=0;i<n;i++)
insert_end(sc.nextInt());

show();
insert(5,6);
show();
insert_front(0);
show();
insert_before(head.next.next,-1);
show();
insert_after(head.next,9);
show();
}
}

5.2)

import java.util.*;
class linked
{
static Scanner sc=new Scanner(System.in);
Node head;
public class Node
{
Node next;
int data;
}

public void insert(int d)


{
Node node=new Node();
node.data=d;

if(head==null)
head=node;

else
{
Node n=head;

while(n.next!=null)
{
n=n.next;
}
n.next=node;
}
}

public void insert(int pos,int d)


{
if(pos==0)
insert(d);

else
{
Node node=new Node();
node.data=d;
//node.next=null;
Node n=head;

for(int i=0;i<pos-2;i++)
{
n=n.next;
}
node.next=n.next;
n.next=node;
}
}

void delete(int pos)


{
Node n=head;
Node n1=null;

if(head==null)
System.out.println("nothing to delete: Empty");

else
{
for(int i=0;i<pos-2;i++)
{
n=n.next;

}
n1=n.next;
n.next=n1.next;
System.out.println("deleted element is :"+n1.data);
}
}

public void show()


{
Node n=head;

while(n.next!=null)
{
System.out.println(n.data);
n=n.next;
}
System.out.println(n.data);
}

public static void main(String args[])


{
linked obj=new linked();
obj.insert(4);
obj.insert(5);
obj.insert(6);
obj.insert(7);
obj.insert(4,8);
obj.show();
obj.delete(3);
obj.show();
}
}

7)

import java.util.*;
class circular
{
static Scanner sc=new Scanner(System.in);
static Node tail;

static class Node


{
Node next;
int data;
}

static void add(int d)


{
Node node=new Node();
node.data=d;

if(tail==null)
{
tail=node;
tail.next=node;
}
else
{
node.next=tail.next; //changing the next of the current
node to point at the starting node
tail.next=node; //linking the tail node to the
current node
tail=node; //moving the tail to pointat the
current node
}
}

static void reverse()


{
if(tail==null)
return;

else
{
Node n=tail; //last node of the list
Node curr=n.next; //pointing the current pointer to the
1st node of the list
Node prev=n,next; //previous pointer pointing to the last
node

while(curr!=n) //while the the current pointer does


not reach the last node of the list, i.e the tail
{
next=curr.next; //storing the address of the node next
to current node
curr.next=prev; //changing the next of current to
point at the prev node
prev=curr; //moving the previous to current node
curr=next; //moving the current to the next node
}
curr.next=prev; //in the end, when the curr reaches
the tail, changing the next of tail to point at the previous node
//i.e the node before it,instead of
pointing to the 1st node
}
}

static void show()


{
Node n=tail;
while(n.next!=tail)
{
System.out.print(n.data+" ");
n=n.next;
}
System.out.print(n.data+" ");
System.out.println();
}

public static void main(String args[])


{
System.out.println("enter no of nodes:" );
int n=sc.nextInt();
System.out.println("enter nodes: ");
for(int i=0;i<n;i++)
add(sc.nextInt());
reverse();
show();
}
}

8)

import java.util.*;
class select_search
{
static Scanner sc=new Scanner(System.in);
static int a[],n;

static void search(int k)


{
for(int i=0;i<n;i++)
{
if(a[i]==k)
{
System.out.println("Present at pos: "+(i+1));
return;
}
}
System.out.println("not present");
}

public static void main(String args[])


{
System.out.println("enter size of the array: ");
n=sc.nextInt();
a=new int[n];
System.out.println("enter array elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

System.out.println("enter element to be searched: ");


int s=sc.nextInt();

search(s);

}
}

8.1)

import java.util.*;
class bubble_sort
{
static Scanner sc=new Scanner(System.in);
static int a[],n;

static void sort(int b[])


{
int f=0;
label:for(int i=0;i<b.length;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
f=1;
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
if(f==0)
break label;
}
}

public static void main(String args[])


{
System.out.println("enter size of the array: ");
n=sc.nextInt();
a=new int[n];
System.out.println("enter array elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

sort(a);
System.out.println("sorted array is: ");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}

8.3)

import java.util.*;
class select_sort
{
static Scanner sc=new Scanner(System.in);
static int a[],n;

static void sort()


{
for(int i=0;i<n-1;i++)
{
int min=i;
for(int j=i;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
int t=a[min];
a[min]=a[i];
a[i]=t;
}
}

public static void main(String args[])


{
System.out.println("enter size of the array: ");
n=sc.nextInt();
a=new int[n];
System.out.println("enter array elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

sort();
System.out.println("sorted array is: ");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}

8.4)

import java.util.*;
class insert_sort
{
static Scanner sc=new Scanner(System.in);
static int a[],n;

static void sort(int b[])


{
int pos=0;
for(int i=1;i<n;i++)
{
pos=i-1;
int f=a[i];

while(pos>=0 && a[pos]>f)


{
a[pos+1]=a[pos];
pos--;
}
a[pos+1]=f;

}
}

public static void main(String args[])


{
System.out.println("enter size of the array: ");
n=sc.nextInt();
a=new int[n];
System.out.println("enter array elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

sort(a);
System.out.println("sorted array is: ");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}

9)
import java.util.*;
class bin_search
{
static Scanner sc=new Scanner(System.in);
static int a[],n;

static int search(int k,int l, int h)


{
int mid=(l+h)/2;
while(l<h)
{
if(k<a[mid])
return search(k,l,mid-1);

else if(k>a[mid])
return search(k,mid+1,h);

}
return mid+1;

public static void main(String args[])


{
System.out.println("enter size of the array: ");
n=sc.nextInt();
a=new int[n];
System.out.println("enter array elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();

System.out.println("enter element to be searched: ");


int s=sc.nextInt();

System.out.println("position is: "+search(s,0,n-1));

}
}

10)

11)

class quickSort
{
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j&lt;high; j++)
{
if (arr[j] &lt;= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high)
{
if (low &lt; high)
{
int pi = partition(arr, low, high);

sort(arr, low, pi-1);


sort(arr, pi+1, high);

}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i&lt;n; ++i)
System.out.print(arr[i]+&quot; &quot;);
System.out.println();
}
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
quickSort ob = new quickSort();
ob.sort(arr, 0, n-1);
System.out.println(&quot;sorted array&quot;);
printArray(arr);
}
}

12)

Import java.io.*;
class MatrixChainMultiplication
{
static int MatrixChainOrder(int p[], int n)
{
int m[][] = new int[n][n];
int i, j, k, L, q;
for (i = 1; i &lt; n; i++)
m[i][i] = 0;
for (L = 2; L &lt; n; L++) {
for (i = 1; i &lt; n - L + 1; i++) {
j = i + L - 1;
if (j == n)
continue;
m[i][j] = Integer.MAX_VALUE;
for (k = i; k &lt;= j - 1; k++) {
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q &lt; m[i][j])
m[i][j] = q;
}
}
}
return m[1][n - 1];
}
public static void main(String args[]) {
int arr[] = new int[] { 20, 15, 30, 5, 40 };
int size = arr.length;
System.out.println(&quot;Minimum number of multiplications is &quot;
+ MatrixChainOrder(arr, size));
}
}

13)

public class NQueenProblem {


final int N = 8;

/* A utility function to print solution */


void printSolution(int board[][])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j]
+ " ");
System.out.println();
}
}

/* A utility function to check if a queen can


be placed on board[row][col]. */
boolean isSafe(int board[][], int row, int col)
{
int i, j;

/* Check this row on left side */


for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;

/* Check upper diagonal on left side */


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;

/* Check lower diagonal on left side */


for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1)
return false;

return true;
}

/* A recursive utility function to solve N


Queen problem */
boolean solveNQUtil(int board[][], int col)
{
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;

/* Consider this column and try placing


this queen in all rows one by one */
for (int i = 0; i < N; i++) {
/* Check if the queen can be placed on
board[i][col] */
if (isSafe(board, i, col)) {
/* Place this queen in board[i][col] */
board[i][col] = 1;

/* recur to place rest of the queens */


if (solveNQUtil(board, col + 1) == true)
return true;

/* If placing queen in board[i][col]


doesn't lead to a solution then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
}
}

/* If the queen can not be placed in any row in


this colum col, then return false */
return false;
}

/* It returns false if queens cannot be placed, otherwise, return


true and
prints placement of queens in the form of 1s.*/
boolean solveNQ()
{
int board[][] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
System.out.print("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

public static void main(String args[])


{
NQueenProblem Queen = new NQueenProblem();
Queen.solveNQ();
}
}

14)

import java.util.*;
import java.lang.*;
import java.io.*;

class MST {
// Number of vertices in the graph
private static final int V = 5;

// A function to find the vertex with minimum key


// value, from the set of vertices not yet included in MST
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}

return min_index;
}

// A function to print the constructed MST stored in parent[]


void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t" +
graph[i][parent[i]]);
}

// Function to construct and print MST for a graph represented


// using adjacency matrix representation
void primMST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];

// Key values used to pick minimum weight edge in cut


int key[] = new int[V];

// To represent set of vertices included in MST


Boolean mstSet[] = new Boolean[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}

// Always include first 1st vertex in MST.


key[0] = 0; // Make key 0 so that this vertex is
// picked as first vertex
parent[0] = -1; // First node is always root of MST

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of the adjacent


// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent vertices


of m
// mstSet[v] is false for vertices not yet included in
MST
// Update the key only if graph[u][v] is smaller than
key[v]
if (graph[u][v] != 0 && mstSet[v] == false &&
graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}

// print the constructed MST


printMST(parent, graph);
}

public static void main(String[] args)


{

MST t = new MST();


int graph[][] = new int[][] { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


t.primMST(graph);
}
}

15)

import java.util.*;

class GFG
{

static int N = 4;

// final_path[] stores the final solution ie, the


// path of the salesman.
static int final_path[] = new int[N + 1];

// visited[] keeps track of the already visited nodes


// in a particular path
static boolean visited[] = new boolean[N];

// Stores the final minimum weight of shortest tour.


static int final_res = Integer.MAX_VALUE;

// Function to copy temporary solution to


// the final solution
static void copyToFinal(int curr_path[])
{
for (int i = 0; i < N; i++)
final_path[i] = curr_path[i];
final_path[N] = curr_path[0];
}

// Function to find the minimum edge cost


// having an end at the vertex i
static int firstMin(int adj[][], int i)
{
int min = Integer.MAX_VALUE;
for (int k = 0; k < N; k++)
if (adj[i][k] < min && i != k)
min = adj[i][k];
return min;
}

// function to find the second minimum edge cost


// having an end at the vertex i
static int secondMin(int adj[][], int i)
{
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int j=0; j<N; j++)
{
if (i == j)
continue;

if (adj[i][j] <= first)


{
second = first;
first = adj[i][j];
}
else if (adj[i][j] <= second &&
adj[i][j] != first)
second = adj[i][j];
}
return second;
}

// function that takes as arguments:


// curr_bound -> lower bound of the root node
// curr_weight-> stores the weight of the path so far
// level-> current level while moving in the search
// space tree
// curr_path[] -> where the solution is being stored which
// would later be copied to final_path[]
static void TSPRec(int adj[][], int curr_bound, int curr_weight,
int level, int curr_path[])
{
// base case is when we have reached level N which
// means we have covered all the nodes once
if (level == N)
{
// check if there is an edge from last vertex in
// path back to the first vertex
if (adj[curr_path[level - 1]][curr_path[0]] != 0)
{
// curr_res has the total weight of the
// solution we got
int curr_res = curr_weight +
adj[curr_path[level-1]][curr_path[0]];

// Update final result and final path if


// current result is better.
if (curr_res < final_res)
{
copyToFinal(curr_path);
final_res = curr_res;
}
}
return;
}

// for any other level iterate for all vertices to


// build the search space tree recursively
for (int i = 0; i < N; i++)
{
// Consider next vertex if it is not same (diagonal
// entry in adjacency matrix and not visited
// already)
if (adj[curr_path[level-1]][i] != 0 &&
visited[i] == false)
{
int temp = curr_bound;
curr_weight += adj[curr_path[level - 1]][i];

// different computation of curr_bound for


// level 2 from the other levels
if (level==1)
curr_bound -= ((firstMin(adj, curr_path[level - 1]) +
firstMin(adj, i))/2);
else
curr_bound -= ((secondMin(adj, curr_path[level - 1]) +
firstMin(adj, i))/2);

// curr_bound + curr_weight is the actual lower bound


// for the node that we have arrived on
// If current lower bound < final_res, we need to
explore
// the node further
if (curr_bound + curr_weight < final_res)
{
curr_path[level] = i;
visited[i] = true;

// call TSPRec for the next level


TSPRec(adj, curr_bound, curr_weight, level + 1,
curr_path);
}

// Else we have to prune the node by resetting


// all changes to curr_weight and curr_bound
curr_weight -= adj[curr_path[level-1]][i];
curr_bound = temp;

// Also reset the visited array


Arrays.fill(visited,false);
for (int j = 0; j <= level - 1; j++)
visited[curr_path[j]] = true;
}
}
}

// This function sets up final_path[]


static void TSP(int adj[][])
{
int curr_path[] = new int[N + 1];

// Calculate initial lower bound for the root node


// using the formula 1/2 * (sum of first min +
// second min) for all edges.
// Also initialize the curr_path and visited array
int curr_bound = 0;
Arrays.fill(curr_path, -1);
Arrays.fill(visited, false);

// Compute initial bound


for (int i = 0; i < N; i++)
curr_bound += (firstMin(adj, i) +
secondMin(adj, i));

// Rounding off the lower bound to an integer


curr_bound = (curr_bound==1)? curr_bound/2 + 1 :
curr_bound/2;

// We start at vertex 1 so the first vertex


// in curr_path[] is 0
visited[0] = true;
curr_path[0] = 0;

// Call to TSPRec for curr_weight equal to


// 0 and level 1
TSPRec(adj, curr_bound, 0, 1, curr_path);
}

// Driver code
public static void main(String[] args)
{
//Adjacency matrix for the given graph
int adj[][] = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0} };

TSP(adj);
System.out.printf("Minimum cost : %d\n", final_res);
System.out.printf("Path Taken : ");
for (int i = 0; i <= N; i++)
{
System.out.printf("%d ", final_path[i]);
}
}
}

16)

import java.util.Arrays;
import java.util.Comparator;

// Greedy approach
public class FractionalKnapSack
{
// function to get maximum value
private static double getMaxValue(int[] wt, int[] val,
int capacity)
{
ItemValue[] iVal = new ItemValue[wt.length];

for (int i = 0; i < wt.length; i++) {


iVal[i] = new ItemValue(wt[i], val[i], i);
}

// sorting items by value;


Arrays.sort(iVal, new Comparator<ItemValue>() {
@Override
public int compare(ItemValue o1, ItemValue o2)
{
return o2.cost.compareTo(o1.cost);
}
});

double totalValue = 0d;

for (ItemValue i : iVal) {

int curWt = (int)i.wt;


int curVal = (int)i.val;

if (capacity - curWt >= 0)


{
// this weight can be picked while
capacity = capacity - curWt;
totalValue += curVal;
}
else
{
// item cant be picked whole
double fraction
= ((double)capacity / (double)curWt);
totalValue += (curVal * fraction);
capacity
= (int)(capacity - (curWt * fraction));
break;
}
}

return totalValue;
}

// item value class


static class ItemValue
{
Double cost;
double wt, val, ind;

// item value function


public ItemValue(int wt, int val, int ind)
{
this.wt = wt;
this.val = val;
this.ind = ind;
cost = new Double((double)val / (double)wt);
}
}

// Driver code
public static void main(String[] args)
{
int[] wt = { 10, 40, 20, 30 };
int[] val = { 60, 40, 100, 120 };
int capacity = 50;

double maxValue = getMaxValue(wt, val, capacity);

// Function call
System.out.println("Maximum value we can obtain = "
+ maxValue);
}
}

17)

import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list


// representation
class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists

// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w)
{
adj[v].add(w);
}

// prints BFS traversal from a given source s


void BFS(int s)
{
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];

// Create a queue for BFS


LinkedList<Integer> queue = new LinkedList<Integer>();

// Mark the current node as visited and enqueue it


visited[s]=true;
queue.add(s);

while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");

// Get all adjacent vertices of the dequeued vertex s


// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}

// Driver method to
public static void main(String args[])
{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal "+


"(starting from vertex 2)");
g.BFS(2);
}
}

18)

import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list


// representation
class Graph
{
private int V; // No. of vertices

// Array of lists for Adjacency List Representation


private LinkedList<Integer> adj[];

// Constructor
@SuppressWarnings("unchecked")
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

//Function to add an edge into the graph


void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
}

// A function used by DFS


void DFSUtil(int v,boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v+" ");

// Recur for all the vertices adjacent to this vertex


Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

// The function to do DFS traversal. It uses recursive DFSUtil()


void DFS(int v)
{
// Mark all the vertices as not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];
// Call the recursive helper function to print DFS traversal
DFSUtil(v, visited);
}

public static void main(String args[])


{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Depth First Traversal "+


"(starting from vertex 2)");

g.DFS(2);
}
}

18.1)

import java.util.*;
import java.lang.*;
import java.io.*;

class ShortestPath {
// A utility function to find the vertex with minimum distance
value,
// from the set of vertices not yet included in shortest path tree
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[])
{
System.out.println("Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " + dist[i]);
}

// Function that implements Dijkstra's single source shortest path


// algorithm for a graph represented using adjacency matrix
// representation
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; // The output array. dist[i] will hold
// the shortest distance from src to i

// sptSet[i] will true if vertex i is included in shortest


// path tree or shortest distance from src to i is finalized
Boolean sptSet[] = new Boolean[V];

// Initialize all distances as INFINITE and stpSet[] as false


for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet, there is an


// edge from u to v, and total weight of path from src
to
// v through u is smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] != 0 && dist[u] !=
Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist);
}

// Driver method
public static void main(String[] args)
{
/* Let us create the example graph discussed above */
int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}

18.2)

import java.util.*;
import java.lang.*;
import java.io.*;

// A class to represent a connected, directed and weighted graph


class Graph {
// A class to represent a weighted edge in graph
class Edge {
int src, dest, weight;
Edge()
{
src = dest = weight = 0;
}
};

int V, E;
Edge edge[];

// Creates a graph with V vertices and E edges


Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}

// The main function that finds shortest distances from src


// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void BellmanFord(Graph graph, int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];

// Step 1: Initialize distances from src to all other


// vertices as INFINITE
for (int i = 0; i < V; ++i)
dist[i] = Integer.MAX_VALUE;
dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times. A simple


// shortest path from src to any other vertex can
// have at-most |V| - 1 edges
for (int i = 1; i < V; ++i) {
for (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight <
dist[v])
dist[v] = dist[u] + weight;
}
}

// Step 3: check for negative-weight cycles. The above


// step guarantees shortest distances if graph doesn't
// contain negative weight cycle. If we get a shorter
// path, then there is a cycle.
for (int j = 0; j < E; ++j) {
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight <
dist[v]) {
System.out.println("Graph contains negative weight
cycle");
return;
}
}
printArr(dist, V);
}

// A utility function used to print the solution


void printArr(int dist[], int V)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}

// Driver method to test above function


public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph

Graph graph = new Graph(V, E);

// add edge 0-1 (or A-B in above figure)


graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = -1;

// add edge 0-2 (or A-C in above figure)


graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 4;

// add edge 1-2 (or B-C in above figure)


graph.edge[2].src = 1;
graph.edge[2].dest = 2;
graph.edge[2].weight = 3;

// add edge 1-3 (or B-D in above figure)


graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 2;

// add edge 1-4 (or A-E in above figure)


graph.edge[4].src = 1;
graph.edge[4].dest = 4;
graph.edge[4].weight = 2;

// add edge 3-2 (or D-C in above figure)


graph.edge[5].src = 3;
graph.edge[5].dest = 2;
graph.edge[5].weight = 5;

// add edge 3-1 (or D-B in above figure)


graph.edge[6].src = 3;
graph.edge[6].dest = 1;
graph.edge[6].weight = 1;

// add edge 4-3 (or E-D in above figure)


graph.edge[7].src = 4;
graph.edge[7].dest = 3;
graph.edge[7].weight = -3;

graph.BellmanFord(graph, 0);
}
}

19)

class BinarySearchTree {

/* Class containing left and right child of current node and key
value*/
class Node {
int key;
Node left, right;

public Node(int item) {


key = item;
left = right = null;
}
}

// Root of BST
Node root;

// Constructor
BinarySearchTree() {
root = null;
}

// This method mainly calls insertRec()


void insert(int key) {
root = insertRec(root, key);
}

/* A recursive function to insert a new key in BST */


Node insertRec(Node root, int key) {
/* If the tree is empty, return a new node */
if (root == null) {
root = new Node(key);
return root;
}

/* Otherwise, recur down the tree */


if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);

/* return the (unchanged) node pointer */


return root;
}

// This method mainly calls InorderRec()


void inorder() {
inorderRec(root);
}

// A utility function to do inorder traversal of BST


void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}

// Driver Program to test above functions


public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();

tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

// print inorder traversal of the BST


tree.inorder();
}
}

19.1)

class BinarySearchTree
{
/* Class containing left and right child of current node and key
value*/
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}

// Root of BST
Node root;

// Constructor
BinarySearchTree()
{
root = null;
}

// This method mainly calls deleteRec()


void deleteKey(int key)
{
root = deleteRec(root, key);
}

/* A recursive function to insert a new key in BST */


Node deleteRec(Node root, int key)
{
/* Base Case: If the tree is empty */
if (root == null) return root;

/* Otherwise, recur down the tree */


if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);

// if key is same as root's key, then This is the node


// to be deleted
else
{
// node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;

// node with two children: Get the inorder successor


(smallest
// in the right subtree)
root.key = minValue(root.right);

// Delete the inorder successor


root.right = deleteRec(root.right, root.key);
}

return root;
}

int minValue(Node root)


{
int minv = root.key;
while (root.left != null)
{
minv = root.left.key;
root = root.left;
}
return minv;
}

// This method mainly calls insertRec()


void insert(int key)
{
root = insertRec(root, key);
}

/* A recursive function to insert a new key in BST */


Node insertRec(Node root, int key)
{

/* If the tree is empty, return a new node */


if (root == null)
{
root = new Node(key);
return root;
}

/* Otherwise, recur down the tree */


if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);

/* return the (unchanged) node pointer */


return root;
}

// This method mainly calls InorderRec()


void inorder()
{
inorderRec(root);
}
// A utility function to do inorder traversal of BST
void inorderRec(Node root)
{
if (root != null)
{
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}

// Driver Program to test above functions


public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

System.out.println("Inorder traversal of the given tree");


tree.inorder();

System.out.println("\nDelete 20");
tree.deleteKey(20);
System.out.println("Inorder traversal of the modified tree");
tree.inorder();

System.out.println("\nDelete 30");
tree.deleteKey(30);
System.out.println("Inorder traversal of the modified tree");
tree.inorder();

System.out.println("\nDelete 50");
tree.deleteKey(50);
System.out.println("Inorder traversal of the modified tree");
tree.inorder();
}
}

20)

public class NaiveSearch {

public static void search(String txt, String pat)


{
int M = pat.length();
int N = txt.length();

/* A loop to slide pat one by one */


for (int i = 0; i <= N - M; i++) {

int j;

/* For current index i, check for pattern


match */
for (j = 0; j < M; j++)
if (txt.charAt(i + j) != pat.charAt(j))
break;

if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]


System.out.println("Pattern found at index " + i);
}
}

public static void main(String[] args)


{
String txt = "AABAACAADAABAAABAA";
String pat = "AABA";
search(txt, pat);
}
} The best case occurs when the first character of the pattern is not
present in text at all.

txt[] = "AABCCAADDEE";
pat[] = "FAA";
The number of comparisons in best case is O(n).
The worst case of Naive Pattern Searching occurs in following
scenarios.
1) When all characters of the text and pattern are same.

txt[] = "AAAAAAAAAAAAAAAAAA";
pat[] = "AAAAA";
2) Worst case also occurs when only the last character is different.
txt[] = "AAAAAAAAAAAAAAAAAB";
pat[] = "AAAAB";
The number of comparisons in the worst case is O(m*(n-m+1)).

20.1)

public class Main


{
// d is the number of characters in the input alphabet
public final static int d = 256;

/* pat -> pattern


txt -> text
q -> A prime number
*/
static void search(String pat, String txt, int q)
{
int M = pat.length();
int N = txt.length();
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;

// The value of h would be "pow(d, M-1)%q"


for (i = 0; i < M-1; i++)
h = (h*d)%q;

// Calculate the hash value of pattern and first


// window of text
for (i = 0; i < M; i++)
{
p = (d*p + pat.charAt(i))%q;
t = (d*t + txt.charAt(i))%q;
}

// Slide the pattern over text one by one


for (i = 0; i <= N - M; i++)
{

// Check the hash values of current window of text


// and pattern. If the hash values match then only
// check for characters on by one
if ( p == t )
{
/* Check for characters one by one */
for (j = 0; j < M; j++)
{
if (txt.charAt(i+j) != pat.charAt(j))
break;
}

// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]


if (j == M)
System.out.println("Pattern found at index " + i);
}

// Calculate hash value for next window of text: Remove


// leading digit, add trailing digit
if ( i < N-M )
{
t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q;

// We might get negative value of t, converting it


// to positive
if (t < 0)
t = (t + q);
}
}
}

/* Driver Code */
public static void main(String[] args)
{
String txt = "GEEKS FOR GEEKS";
String pat = "GEEK";

// A prime number
int q = 101;

// Function Call
search(pat, txt, q);
}
} The average and best-case running time of the
Rabin-Karp algorithm is O(n+m), but its worst-case time is O(nm). Worst
case of Rabin-Karp algorithm occurs when all characters of pattern and
text are same as the hash values of all the substrings of txt[] match
with hash value of pat[]. For example pat[] = “AAA” and txt[] =
“AAAAAAA”.

20.2)

class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();

// create lps[] that will hold the longest


// prefix suffix values for pattern
int lps[] = new int[M];
int j = 0; // index for pat[]

// Preprocess the pattern (calculate lps[]


// array)
computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]


while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
System.out.println("Found pattern "
+ "at index " + (i - j));
j = lps[j - 1];
}

// mismatch after j matches


else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}

void computeLPSArray(String pat, int M, int lps[])


{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0

// the loop calculates lps[i] for i = 1 to M-1


while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];

// Also, note that we do not increment


// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}

// Driver program to test above function


public static void main(String args[])
{
String txt = "ABABDABACDABABCABAB";
String pat = "ABABCABAB";
new KMP_String_Matching().KMPSearch(pat, txt);
}
} The KMP matching algorithm uses
degenerating property (pattern having same sub-patterns appearing more
than once in the pattern) of the pattern and improves the worst case
complexity to O(n).

10)

class MergeSort {
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int[n1];
int R[] = new int[n2];

/*Copy data to temp arrays*/


for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarry array


int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

/* Copy remaining elements of R[] if any */


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r) {
// Find the middle point
int m = (l + r) / 2;

// Sort first and second halves


sort(arr, l, m);
sort(arr, m + 1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6, 7 };

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length - 1);

System.out.println("\nSorted array");
printArray(arr);
}
}

You might also like