Data Structures Using Java Lab
Data Structures Using Java Lab
Laboratory Manual
Enrollment No:
Name:
Certificate
This is to certify that the Lab/term work carried out in the subject of
DATA STRUCTURES USING JAVA LAB and recorded in this journal is the
INDEX
S.NO DATE EXPERIMENT NAME SIGN REMARKS
1. Write Java programs that use both recursive and non-
recursive functions for implementing
the following searching methods:
(a) Linear search (b) Binary search
2. Write Java programs to implement the following using arrays
and linked lists List ADT
a) List using Arrays
b) List Using LinkedList
3. Write Java programs to implement the following using an
array.
(a) Stack ADT (b) Queue ADT
4. Write a java program that reads an infix expression, converts
the expression to postfix form
and then evaluates the postfix expression (use stack ADT).
5. Write Java programs to implement the following using a
singly linked list.
(a) Stack ADT (b) Queue ADT
6. Write Java programs to implement the deque (double ended
queue) ADT using
(a) Array
(b) Doubly linked list.
7. Write a Java program to implement a priority queue ADT
11. write a java program for implementation of bfs and dfs for a
given graph
12. write a java program for implementing the following sorting
methods:
a)Bubble sort
b)Selection sort
c)Insertion sort
13. write a java program for implementing kmp pattern matching
algorithm
1. Write Java programs that use both recursive and non-recursive functions
for implementing
the following searching methods:
(a) Linear search (b) Binary search
import java.io.*;
class LinearSearch
{
public static void main(String args[]) throws IOException
{
int count=0;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
int key=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
if(arr[i]==key)
System.out.println("element found : " + key + " in position :" + (i+1));
else
count++;
}
if(count==n)
System.out.println(key + " element not found, search failed");
}
}
OUTPUT:
import java.io.*;
class RecursiveLinearSearch
{
public static int arr[], key;
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
key=Integer.parseInt(br.readLine());
if( linearSearch(arr.length-1) )
System.out.println(key + " found in the list" );
else
System.out.println(key + " not found in the list");
}
static boolean linearSearch(int n)
{
if( n < 0 ) return false;
if(key == arr[n])
return true;
else
return linearSearch(n-1);
}
}
OUTPUT:
OUTPUT:
import java.io.*;
class RecursiveBinarySearch
{
public static int arr[], key;
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
key=Integer.parseInt(br.readLine());
if( binarySearch(0, arr.length-1) )
System.out.println(key + " found in the list");
else
System.out.println(key + " not found in the list");
}
static boolean binarySearch(int low, int high)
{
if( low > high ) return false;
int mid = (low + high)/2;
int c = ((Comparable)key).compareTo(arr[mid]);
if( c < 0) return binarySearch(low, mid-1);
else if( c > 0) return binarySearch(mid+1, high);
2. Write Java programs to implement the following using arrays and linked lists List ADT
a) List using Arrays
//List.java
public interface List
{
public void createList(int n);
public void insertFirst(Object ob);
public void insertAfter(Object ob, Object pos);
public Object deleteFirst();
public Object deleteAfter(Object pos);
public boolean isEmpty();
public int size();
}
// ArrayList.java
class ArrayList implements List
{
class Node
{
Object data;
int next;
Node(Object ob, int i) // constructor
{
data = ob;
next = i;
}
}
int MAXSIZE; // max number of nodes in the list
Node list[]; // create list array
int head, count; // count: current number of nodes in the list
ArrayList( int s) // constructor
{
MAXSIZE = s;
list = new Node[MAXSIZE];
}
public void initializeList()
{
for( int p = 0; p < MAXSIZE-1; p++ )
list[p] = new Node(null, p+1);
list[MAXSIZE-1] = new Node(null, -1);
}
public void createList(int n) // create ‘n’ nodes
{
int p;
for( p = 0; p < n; p++ )
{
list[p] = new Node(11+11*p, p+1);
count++;
}
list[p-1].next = -1; // end of the list
}
public void insertFirst(Object item)
{
OUTPUT:
if( p == null )
System.out.println(key + " key is not found");
else
{
Node q = new Node(item); // create new node
q.next = p.next; // new node next refers to p.next
p.next = q; // p.next refers to new node
count++;
}
}
public Node find(Object key)
{
p = head;
while( p != null ) // start at beginning of list until end of list
{
if( p.data == key ) return p; // if found, return key address
p = p.next; // move to next node
}
return null; // if key search is unsuccessful, return null
}
public Object deleteFirst() // delete first node
{
if( isEmpty() )
{
System.out.println("List is empty: no deletion");
return null;
}
Node tmp = head; // tmp saves reference to head
head = tmp.next;
count--;
return tmp.data;
}
public Object deleteAfter(Object key) // delete node after key item
{
p = find(key); // p = “location of key node”
if( p == null )
{
System.out.println(key + " key is not found");
return null;
}
if( p.next == null ) // if(there is no node after key node)
{
System.out.println("No deletion");
return null;
}
else
{
Node tmp = p.next; // save node after key node
p.next = tmp.next; // point to next of node deleted
count--;
return tmp.data; // return deleted node
}
}
public void displayList()
{
p = head; // assign mem. address of 'head' to 'p'
System.out.print("\nLinked List: ");
while( p != null ) // start at beginning of list until end of list
{
System.out.print(p.data + " -> "); // print data
p = p.next; // move to next node
}
System.out.println(p); // prints 'null'
}
public boolean isEmpty() // true if list is empty
{
return (head == null);
}
public int size()
{
return count;
}
} // end of LinkeList class
class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList list = new LinkedList(); // create list object
list.createList(4); // create 4 nodes
list.displayList();
list.insertFirst(55); // insert 55 as first node
list.displayList();
list.insertAfter(66, 33); // insert 66 after 33
list.displayList();
Object item = list.deleteFirst(); // delete first node
if( item != null )
{
System.out.println("deleteFirst(): " + item);
list.displayList();
}
item = list.deleteAfter(22); // delete a node after node(22)
if( item != null )
{
System.out.println("deleteAfter(22): " + item);
list.displayList();
}
System.out.println("size(): " + list.size());
}
}
OUTPUT:
return stack[top];
else
{
System.out.println("stack is empty");
return -1;
}
}
void size()
{
System.out.println("size of the stack is :"+(top+1));
}
void display()
{
if(!isempty())
{
for(int i=top;i>=0;i--)
System.out.print(stack[i]+" ");
}
else
System.out.println("stack is empty");
}
}
class stacktest
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of stack");
int size=Integer.parseInt(br.readLine());
stackclass s=new stackclass(size);
int ch,ele;
do
{
System.out.println();
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.peek");
System.out.println("4.size");
System.out.println("5.display");
System.out.println("6.is empty");
System.out.println("7.is full");
System.out.println("8.exit");
System.out.println("enter ur choise :");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:if(!s.isfull())
{
System.out.println("enter the element to insert: ");
ele=Integer.parseInt(br.readLine());
s.push(ele);
}
else
{
System.out.print("stack is overflow");
}
break;
case 2:int del=s.pop();
if(del!=-1)
System.out.println(del+" is deleted");
break;
case 3:int p=s.peek();
if(p!=-1)
System.out.println("peek element is: +p);
break;
case 4:s.size();
break;
case 5:s.display();
break;
}
}while(ch!=0);
}
}
OUTPUT:
{
max=n;
que=new int[max];
front=rear=-1;
}
boolean isfull()
{
if(rear==(max-1))
return true;
else
return false;
}
boolean isempty()
{
if(front==-1)
return true;
else
return false;
}
void insert(int n)
{
if(isfull())
System.out.println("list is full");
else
{
rear++;
que[rear]=n;
if(front==-1)
front=0;
count++;
}
}
int delete()
{
int x;
if(isempty())
return -1;
else
{
x=que[front];
que[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
count--;
}
return x;
}
void display()
{
if(isempty())
System.out.println("queue is empty");
else
for(int i=front;i<=rear;i++)
System.out.println(que[i]);
}
int size()
{
return count;
}
public static void main(String args[])
{
int ch;
Scanner s=new Scanner(System.in);
System.out.println("enter limit");
int n=s.nextInt();
queue q=new queue(n);
do
{
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
System.out.println("enter ur choise :");
ch=s.nextInt();
switch(ch)
{
case 1:System.out.println("enter element :");
int n1=s.nextInt();
q.insert(n1);
break;
OUTPUT:
4. Write a java program that reads an infix expression, converts the expression to postfix form
and then evaluates the postfix expression (use stack ADT).
import java.io.*;
class InfixToPostfix
{
java.util.Stack<Character> stk =new java.util.Stack<Character>();
public String toPostfix(String infix)
{
infix = "(" + infix + ")"; // enclose infix expr within parentheses
String postfix = "";
/* scan the infix char-by-char until end of string is reached */
for( int i=0; i<infix.length(); i++)
{
char ch, item;
ch = infix.charAt(i);
if( isOperand(ch) ) // if(ch is an operand), then
postfix = postfix + ch; // append ch to postfix string
if( ch == '(' ) // if(ch is a left-bracket), then
stk.push(ch); // push onto the stack
if( isOperator(ch) ) // if(ch is an operator), then
{
item = stk.pop(); // pop an item from the stack
/* if(item is an operator), then check the precedence of ch and item*/
if( isOperator(item) )
{
if( precedence(item) >= precedence(ch) )
{
stk.push(item);
stk.push(ch);
}
else
{
postfix = postfix + item;
stk.push(ch);
}
}
else
{
stk.push(item);
stk.push(ch);
}
} // end of if(isOperator(ch))
if( ch == ')' )
{
item = stk.pop();
while( item != '(' )
{
} // end of for-loop
return postfix;
} // end of toPostfix() method
public boolean isOperand(char c)
{
return(c >= 'A' && c <= 'Z');
}
public boolean isOperator(char c)
{
return( c=='+' || c=='-' || c=='*' || c=='/' );
}
public int precedence(char c)
{
int rank = 1; // rank = 1 for '*’ or '/'
if( c == '+' || c == '-' ) rank = 2;
return rank;
}
}
//InfixToPostfixDemo.java
class InfixToPostfixDemo
{
public static void main(String args[]) throws IOException
{
InfixToPostfix obj = new InfixToPostfix();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Expression:");
String infix = br.readLine();
//String infix = "A*(B+C/D)-E";
System.out.println("infix: " + infix );
System.out.println("postfix:"+obj.toPostfix(infix) );
}
}
OUTPUT:
5. Write Java programs to implement the following using a singly linked list.
if(top==null)
return true;
else
return false;
}
void display()
{
Stack1 ptr;
for(ptr=top;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
public static void main(String args[ ])throws Exception
{
int x;
int ch;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Stack1 a=new Stack1();
do{
System.out.println("enter 1 for pushing");
System.out.println("enter 2 for poping");
System.out.println("enter 3 for isEmpty");
System.out.println("enter 4 for display");
System.out.println("Enter 0 for exit");
System.out.println("enter ur choice ");
ch=Integer.parseInt(b.readLine());
switch(ch)
{
case 1:System.out.println("enter element to insert");
int e=Integer.parseInt(b.readLine());
a.push(e);
break;
case 2:if(!a.isEmpty())
{
int p=a.pop();
System.out.println("deleted element is "+p);
}
else
{
System.out.println("stack is empty");
}
break;
case 3:System.out.println(a.isEmpty());
break;
case 4:if(!a.isEmpty())
{
a.display();
}
else
{
System.out.println("list is empty");
}
}
}while(ch!=0);
}
}
OUTPUT:
5 (b). Queue
import java.io.*;
class Qlnk
{
Qlnk front,rear,next;
int data;
Qlnk()
{
data=0;
next=null;
}
Qlnk(int d)
{
data=d;
next=null;
}
Qlnk getFront()
{
return front;
}
Qlnk getRear()
{
return rear;
}
void insertelm(int item)
{
Qlnk nn;
nn=new Qlnk(item);
if(isEmpty())
{
front=rear=nn;
}
else
{
rear.next=nn;
rear=nn;
}
}
int delelm()
{
if(isEmpty())
{
System.out.println("deletion failed");
return -1;
}
else
{
int k=front.data;
if(front!=rear)
front=front.next;
else
rear=front=null;
return k;
}
}
boolean isEmpty()
{
if(rear==null)
return true;
else
return false;
}
int size()
{
Qlnk ptr;
int cnt=0;
for(ptr=front;ptr!=null;ptr=ptr.next)
cnt++;
return cnt;
}
void display()
{
Qlnk ptr;
if(!isEmpty())
{
for(ptr=front;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
else
System.out.println("q is empty");
}
public static void main(String arr[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Qlnk m=new Qlnk();
int ch;
do
{
System.out.println("enter 1 for insert");
System.out.println("enter 2 for deletion");
System.out.println("enter 3 for getFront");
System.out.println("enter 4 for getRear");
System.out.println("enter 5 for size");
System.out.println("enter 6 for display");
System.out.println("enter 0 for exit");
System.out.println("enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("enter ele to insert");
int item=Integer.parseInt(br.readLine());
m.insertelm(item);break;
case 2:int k=m.delelm();
System.out.println("deleted ele is "+k);break;
case 3:System.out.println("front index is"+(m.getFront()).data);break;
case 4:System.out.println("rear index is"+(m.getRear()).data);break;
case 5:System.out.println("size is"+m.size());break;
case 6:m.display();break;
}
}while(ch!=0);
}
}
6. Write Java programs to implement the deque (double ended queue) ADT using
(a) Array
(b) Doubly linked list.
(a): An ArrayDeque Class
public class ArrayDeque {
private int maxSize;
private Object[] que;
private int first;
private int last;
private int count; // current number of items in deque
public ArrayDeque(int s) { // constructor
maxSize = s;
que = new Object[maxSize];
first = last = -1;
count = 0;
}
public void addLast(Object item) {
if(count == maxSize) {
System.out.println("Deque is full"); return;
}
last = (last+1) % maxSize;
que[last] = item;
if(first == -1 && last == 0) first = 0;
count++;
}
public Object removeLast() {
if(count == 0) {
System.out.println("Deque is empty"); return(' ');
}
Object item = que[last];
que[last] = „ ‟;
if(last > 0)
last = (last-1) % maxSize;
count--;
if(count == 0)
first = last = -1;
return(item);
}
public void addFirst(Object item){
if(count == maxSize){
System.out.println("Deque is full"); return;
}
if(first > 0)
first = (first-1) % maxSize;
else if(first == 0)
first = maxSize-1;
que[first] = item;
count++;
}
}
private DequeNode first, last;
private int count;
public void addFirst(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else {
DequeNode tmp = new DequeNode(item);
tmp.next = first;
first.prev = tmp;
first = tmp;
}
count++;
}
public void addLast(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else{
DequeNode tmp = new DequeNode(item);
tmp.prev = last;
last.next = tmp;
last = tmp;
}
count++;
}
public Object removeFirst(){
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = first.data;
first = first.next;
first.prev = null;
count--;
return item;
}
}
public Object removeLast() {
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = last.data;
last = last.prev;
last.next = null;
count--;
return item;
}
}
public Object getFirst(){
if( !isEmpty() )
return( first.data );
else
return null;
}
public Object getLast(){
if( !isEmpty() )
return( last.data );
else
return null;
}
public boolean isEmpty(){
return (count == 0);
}
public int size(){
return(count);
}
public void display(){
DequeNode p = first;
System.out.print("Deque: [ ");
while( p != null ){
System.out.print( p.data + " " );
p = p.next;
}
System.out.println("]");
}
}
public class LinkedDequeDemo {
public static void main( String args[]){
LinkedDeque dq = new LinkedDeque();
System.out.println("removeFirst():" + dq.removeFirst());
dq.addFirst('A');
dq.addFirst('B');
dq.addFirst('C');
dq.display();
dq.addLast('D');
dq.addLast('E');
System.out.println("getFirst():" + dq.getFirst());
System.out.println("getLast():" + dq.getLast());
dq.display();
System.out.println("removeFirst():"+dq.removeFirst());
System.out.println("removeLast():"+ dq.removeLast());
dq.display();
System.out.println("size():" + dq.size());
}
}
Output:
Deque is empty
removeFirst(): null
Deque: [ C B A ]
getFirst(): C
getLast(): E
Deque: [ C B A D E ]
removeFirst(): C
removeLast(): E
Deque: [ B A D ]
size(): 3
return null;
}
else {
Node tmp = head;
head = head.next;
return tmp;
}
}
public void displayList() {
Node p = head; // assign address of head to p
System.out.print("\nQueue: ");
while( p != null ) // start at beginning of list until end of list
{
System.out.print(p.data+"(" +p.prn+ ")" + " ");
p = p.next; // move to next node
}
System.out.println();
}
public boolean isEmpty() // true if list is empty
{
return (head == null);
}
public Node peek() // get first item
{
return head;
}
class LinkedPriorityQueueDemo {
public static void main(String[] args){
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Babu", 3);
pq.insert("Nitin", 2);
pq.insert("Laxmi", 2);
pq.insert("Kim", 1);
pq.insert("Jimmy", 3);
pq.displayList();
item = pq.delete();
if( item != null )
System.out.println("delete():" + item.data + "(" +item.prn+")");
pq.displayList();
pq.insert("Scot", 2);
pq.insert("Anu", 1);
pq.insert("Lehar", 4);
pq.displayList();
} }
Output:
Queue: Kim(1) Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
delete(): Kim(1)
Queue: Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
Queue: Anu(1) Nitin(2) Laxmi(2) Scot(2) Babu(3) Jimmy(3) Lehar(4)
8. Write Java programs that use recursive and non-recursive functions to traverse the given
binarytree in
APreorder
b) Inorder
c) Postorder.
class Node
{
Object data;
Node left;
Node right;
Node( Object d ) // constructor
{
data = d;
}}
class BinaryTree
{
Object tree[];
int maxSize;
java.util.Stack<Node> stk = new java.util.Stack<Node>();
BinaryTree( Object a[], int n ) // constructor
{
maxSize = n;
tree = new Object[maxSize];
for( int i=0; i<maxSize; i++ )
tree[i] = a[i];
}
public Node buildTree( int index )
{
Node p = null;
if( tree[index] != null )
{
p = new Node(tree[index]);
p.left = buildTree(2*index+1);
p.right = buildTree(2*index+2);
}
return p;
}
/* Recursive methods - Binary tree traversals */
public void inorder(Node p)
{
if( p != null )
{
inorder(p.left);
System.out.print(p.data + " ");
inorder(p.right);
}}
public void preorder(Node p)
{
if( p != null )
{
System.out.print(p.data + " ");
preorder(p.left);
preorder(p.right);
}}
public void postorder(Node p)
{
if( p != null )
{
postorder(p.left);
postorder(p.right);
System.out.print(p.data + " ");
}}
/* Non-recursive methods - Binary tree traversals */
public void preorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
stk.push(p);
while( !stk.isEmpty() )
{
p = stk.pop();
if( p != null )
{
System.out.print(p.data + " ");
stk.push(p.right);
stk.push(p.left);
}}}
public void inorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
while( !stk.isEmpty() || p != null )
{
if( p != null )
{
stk.push(p); // push left-most path onto stack
p = p.left;
}
else
{
p = stk.pop(); // assign popped node to p
System.out.print(p.data + " "); // print node data
p = p.right; // move p to right subtree
}}}
public void postorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
Node tmp = p;
while( p != null )
{
while( p.left != null )
{
stk.push(p);
p = p.left;
}
while( p != null && (p.right == null || p.right == tmp ))
{
System.out.print(p.data + " "); // print node data
tmp = p;
if( stk.isEmpty() )
return;
p = stk.pop();
}
stk.push(p);
p = p.right;
} } } // end of BinaryTree class
class BinaryTreeDemo
{
public static void main(String args[])
{
Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H', null,'B',
null, null, null, null, null, null, null, null, null, null };
BinaryTree t = new BinaryTree( arr, arr.length );
Node root = t.buildTree(0); // buildTree() returns reference to root
System.out.print("\n Recursive Binary Tree Traversals:");
System.out.print("\n inorder: ");
t.inorder(root);
System.out.print("\n preorder: ");
t.preorder(root);
System.out.print("\n postorder: ");
t.postorder(root);
System.out.print("\n Non-recursive Binary Tree Traversals:");
System.out.print("\n inorder: ");
t.inorderIterative(root);
System.out.print("\n preorder: ");
t.preorderIterative(root);
System.out.print("\n postorder: ");
t.postorderIterative(root);
}
}
OUTPUT:
9. write a java program that dispalys node values in a level order traversal (traverse
the tree one level at a time,starting at the root node) for a binary tree
45. // to the leaf node, which is farthest from the root node, gives the
46. // height of the tree
47. int treeHeight(TreeNode r)
48. {
49. if (r == null)
50. {
51. return 0;
52. }
53. else
54. {
55. // finding the height of the left and right subtrees
56. int lh = treeHeight(r.left);
57. int rh = treeHeight(r.right);
58.
59. // picking up the larger one
60. if (lh > rh)
61. {
62. return (lh + 1);
63. }
64. else
65. {
66. return (rh + 1);
67. }
68. }
69. }
70.
71. // Printing nodes present in the current level
72. void displayCurrentLevel(TreeNode r, int l)
73. {
74. // null means nothing is there to print
75. if (r == null)
76. {
77. return;
78. }
79.
80. // l == 1 means only one node
81. // is present in the binary tree
82. if (l == 1)
83. {
84. System.out.print(r.val + " ");
85. }
86.
87. // l > 1 means either there are nodes present in
88. // the left side of the current node or in the
89. // right side of the current node or in both sides
90. // therefore, we have to look in the left as well as in
class BST_class {
//node class that defines BST node
class Node {
int key;
Node left, right;
return root;
}
11. write a java program for implementation of bfs and dfs for a
given graph
BFS Algorithm
The general process of exploring a graph using breadth-first search includes the following steps:-
Take the input for the adjacency matrix or adjacency list for the graph.
Initialize a queue.
Enqueue the root node (in other words, put the root node into the beginning of the queue).
Dequeue the head (or first element) of the queue, then enqueue all of its neighboring nodes,
starting from left to right. If a node has no neighboring nodes which need to be explored, simply
dequeue the head and continue the process. (Note: If a neighbor which is already explored or in
the queue appears, don’t enqueue it – simply skip it.)
Keep repeating this process till the queue is empty.
import java.io.*;
import java.util.*;
class Graph
{
private int V; //number of nodes in the
graph
private LinkedList<Integer> adj[]; //adjacency list
private Queue<Integer> queue; //maintaining a queue
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>();
}
queue = new LinkedList<Integer>();
}
void BFS(int n)
{
nodes[n]=true;
queue.add(n); //root node is added to the top of
the queue
while (queue.size() != 0)
{
n = queue.poll(); //remove the top element of the
queue
System.out.print(n+" "); //print the top element of the
queue
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
graph.addEdge(4, 5);
graph.addEdge(3, 5);
graph.addEdge(1, 2);
graph.addEdge(1, 0);
graph.addEdge(2, 1);
graph.addEdge(4, 1);
graph.addEdge(3, 1);
graph.addEdge(5, 4);
graph.addEdge(5, 3);
graph.BFS(0);
}
}
DFS Algorithm
The general process of exploring a graph using depth first search includes the following steps:-
Take the input for the adjacency matrix or adjacency list for the graph.
Initialize a stack.
Push the root node (in other words, put the root node into the beginning of the stack).
If the root node has no neighbors, stop here. Else push the leftmost neighboring node which
hasn’t already been explored into the stack. Continue this process till a node is encountered
which has no neighbors (or whose neighbors have all been added to the stack already) – stop
the process then, pop the head, and then continue the process for the node which is popped.
Keep repeating this process till the stack becomes empty.
import java.io.*;
import java.util.*;
class Graph {
private int V; //number of nodes
public Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
{
adj[i] = new LinkedList();
}
void DFS(int v)
{
boolean already[] = new boolean[V]; //initialize a new
boolean array to store the details of explored nodes
DFSUtil(v, already);
}
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 0);
g.addEdge(1, 3);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 3);
g.addEdge(5, 3);
System.out.println(
"Following is Depth First Traversal: ");
g.DFS(0);
}
}
12. write a java program for implementing the following sorting methods:
a)Bubble sort
b)Selection sort
c)Insertion sort
a)Bubble sort
int n = arr.length;
int temp = 0;
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
System.out.println();
b)Selection sort
1. import java.util.Scanner;
2.
3. public class SelectionSortExample2
4. {
5. public static void main(String args[])
6. {
7. int size, i, j, temp;
8. int arr[] = new int[50];
9. Scanner scan = new Scanner(System.in);
10.
11. System.out.print("Enter Array Size : ");
12. size = scan.nextInt();
13.
14. System.out.print("Enter Array Elements : ");
15. for(i=0; i<size; i++)
16. {
17. arr[i] = scan.nextInt();
18. }
19.
20. System.out.print("Sorting Array using Selection Sort Technique..\n");
21. for(i=0; i<size; i++)
22. {
23. for(j=i+1; j<size; j++)
24. {
25. if(arr[i] > arr[j])
26. {
27. temp = arr[i];
28. arr[i] = arr[j];
29. arr[j] = temp;
30. }
31. }
32. }
33.
34. System.out.print("Now the Array after Sorting is :\n");
35. for(i=0; i<size; i++)
36. {
37. System.out.print(arr[i]+ " ");
38. }
39. }
40. }
c)Insertion sort
13. write a java program for implementing kmp pattern matching algorithm
class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}