DATA STRUCTURES USING JAVA LAB
1
203C1A0405
1a) i.write java program that use non –recursive function for implementation
linear search?
import java.util.Scanner;
class NrLinear
{
public static void main(String[]args)
{
int n,key;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
n = sc.nextInt();
int[]arr = new int[10];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Enter the key element:");
key = sc.nextInt();
int result = search(arr,n,key);
if(result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present at index"+(result));
}
public static int search(int arr[],int n,int key)
{
for(int i=0;i<n;i++)
{
if (arr[i]==key)
return i;
}
return-1;
}
}
DATA STRUCTURES USING JAVA LAB
2
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac NrLinear.java
C:UsersDMSSVHDesktop203C1A0405>java NrLinear
Enter the number of elements:5
Enter the elements of the array:
1 2 3 4 5
Enter the key element:
4
Element is present at index3
DATA STRUCTURES USING JAVA LAB
3
203C1A0405
1a) ii .write java program that use recursive function for implementation linear
search?
import java.util.Scanner;
class RLinear
{
public static void main(String[]args)
{
int n,key;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
n = sc.nextInt();
int[]arr = new int[10];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{arr[i] = sc.nextInt();
}
System.out.println("Enter the key element:");
key = sc.nextInt();
int result = search(arr,n,key);
if(result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present at index"+(result));
}
public static int search(int arr[],int n,int key)
{
n--;
if(n<0)
return-1;
if(arr[n]==key)
return n;
else
return search(arr,n,key);
}
}
DATA STRUCTURES USING JAVA LAB
4
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac RLinear.java
C:UsersDMSSVHDesktop203C1A0405>java RLinear
Enter the number of elements:5
Enter the elements of the array:
10 20 30 40 50
Enter the key element:
50
Element is present at index4
DATA STRUCTURES USING JAVA LAB
5
203C1A0405
1b) i. Write java program that use a non-recursive function for implementing
Binary search?
import java.util.Scanner;
class NrBinary
{
public static void main(String[]args)
{
int n,key;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements:");
n = sc.nextInt();
int[] arr = new int[10];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Enter the key element:");
key = sc.nextInt();
sort(arr,n);
System.out.println("The sorted elements are:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+ " ");
System.out.println();
int result = binarySearch(arr,0,n-1,key);
if(result == -1)
System.out.print("Elements is not present in array");
else
System.out.print("Element is present at index" +(result+1));
}
public static int binarySearch(int arr[], int l, int r, int x)
{
while(l <= r)
{
int mid = (l+r)/2;
if(arr[mid] == x)
return mid;
DATA STRUCTURES USING JAVA LAB
6
203C1A0405
if(arr[mid] > x)
r = mid-1;
else
if(arr[mid] < x)
l = mid+1;
}
return -1;
}
public static void sort(int arr[],int n)
{
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
DATA STRUCTURES USING JAVA LAB
7
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac NrBinary.java
C:UsersDMSSVHDesktop203C1A0405>java NrBinary
Enter the number of elements:
5
Enter the elements of the array:
3 6 1 8 7
Enter the key element:
8
The sorted elements are:
1 3 6 7 8
Element is present at index5
DATA STRUCTURES USING JAVA LAB
8
203C1A0405
1b) ii. Write java program that use a Recursive function for implementing Binary
search?
import java.util.Scanner;
class RBinary
{
public static void main(String[]args)
{
int n,key;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements:");
n = sc.nextInt();
int[]arr = new int[10];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Enter the key element:");
key = sc.nextInt();
sort(arr,n);
System.out.println("The sorted elements are:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+ " ");
System.out.println();
int result = binarySearch(arr,0,n-1,key);
if(result == -1)
System.out.println("Element is not present in array");
else
System.out.println("Element is present at index" +(result+1));
}
public static int binarySearch(int arr[],int l,int x,int r)
{
if(l <= r)
{
int mid = (1+r)/2;
if(arr[mid] == x)
DATA STRUCTURES USING JAVA LAB
9
203C1A0405
return mid;
if(arr[mid] > x)
return binarySearch(arr,l,mid-1,x);
if(arr[mid] < x)
return binarySearch(arr,mid+1,r,x);
}
return-1;
}
public static void sort(int arr[],int n)
{
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
DATA STRUCTURES USING JAVA LAB
10
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac RBinary.java
C:UsersDMSSVHDesktop203C1A0405>java RBinary
Enter the number of elements:
5
Enter the elements of the array:
4 3 6 2 1
Enter the key element:
6
The sorted elements are:
1 2 3 4 6
Element is present at index4
DATA STRUCTURES USING JAVA LAB
11
203C1A0405
3) Write a java programs to implement the following using an array?
a) Stack ADT
import java.util.*;
class MyStack
{
private int top = -1;
int SIZE = 5;
private int stk[] = new int[SIZE];
boolean isFull()
{
if(top == SIZE-1)
return true;
else
return false;
}
boolean isEmpty()
{
if(top == -1)
return true;
else
return false;
}
void push(int num)
{
if(isFull())
{
System.out.println("Stack Overflow");
}
else
{
stk[++top] = num;
System.out.println("n"+num+"is inserted in stack");
}
}
int pop()
{
if(isEmpty())
DATA STRUCTURES USING JAVA LAB
12
203C1A0405
{
System.out.println("n Stack Underflow");
return 0;
}
else
{
int x = stk[top];
top--;
System.out.println("n"+x+"is removed from stack");
return x;
}
}
int peek()
{
if(isEmpty())
{
System.out.println("n Stack Underflow");
return 0;
}
else
{
System.out.println("the top element is:"+stk[top]);
return stk[top];
}
}
void display()
{
if(isEmpty())
{
System.out.println("n Stack Empty");
}
else
{
System.out.println("n Stack:");
for(int i=0;i<=top;i++)
{
System.out.println("|"+stk[i]);
}
}
}
}
class Stack
{
DATA STRUCTURES USING JAVA LAB
13
203C1A0405
public static void main(String[]args)
{
System.out.println("********** stack using Array **********");
boolean flag = true;
Scanner in = new Scanner(System.in);
int ch,num;
MyStack s = new MyStack();
while(flag)
{
System.out.println("n1.PUSHn2.POPn3.PEEKn4.DISPLAYn5.QUITn Enter
your choice:");
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number you want to insert in stack:");
num = in.nextInt();
s.push(num);
break;
case 2:
s.pop();
break;
case 3:
s.peek();
break;
case 4:
s.display();
break;
case 5:
flag = false;
break;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
14
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac Stack.java
C:UsersDMSSVHDesktop203C1A0405>java Stack
********** stack using Array **********
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
1
1is inserted in stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
2
2is inserted in stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
3
DATA STRUCTURES USING JAVA LAB
15
203C1A0405
3is inserted in stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
4
4is inserted in stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
5
5is inserted in stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
Stack:
|1
|2
|3
|4
|5
1.PUSH
DATA STRUCTURES USING JAVA LAB
16
203C1A0405
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
2
5is removed from stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
3
the top element is:4
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:5
DATA STRUCTURES USING JAVA LAB
17
203C1A0405
3) b . Write a java programs to implement the following using an array?
( Queue ADT)
import java.util.*;
class MyQueue
{
private int front = -1,rear = -1;
int SIZE = 5;
private int queue[] = new int[SIZE];
boolean isFull()
{
if(front == 0&&rear == SIZE-1)
return true;
else
return false;
}
boolean isEmpty()
{
if(front == -1)
return true;
else
return false;
}
void enQueue(int num)
{
if(isFull())
{
System.out.println("Queue Overflow");
}
else
{
if(front == -1)
{
front = 0;
}
rear++;
queue[rear] = num;
DATA STRUCTURES USING JAVA LAB
18
203C1A0405
System.out.println("n"+num+"is inserted in queue");
}
}
int deQueue()
{
int x;
if(isEmpty())
{
System.out.println("n Queue Underflow");
return 0;
}
else
{
x = queue[front];
front++;
if(front >= rear)
{
front = -1;
rear = -1;
}
System.out.println("n"+x+"is removed from Queue");
return x;
}
}
int peek()
{
if(isEmpty())
{
System.out.println("n Queue Underflow");
return 0;
}
else
{
System.out.println("the front element is:"+queue[front]);
return queue[front];
}
}
void display()
{
if(isEmpty())
{
System.out.println("n Queue Empty");
}
DATA STRUCTURES USING JAVA LAB
19
203C1A0405
else
{
System.out.println("n Queue:");
for(int i=front;i<=rear;i++)
{
System.out.println("|"+queue[i]);
}
}
}
}
class Queue
{
public static void main(String[]args)
{
System.out.println("********** Queue using Array **********");
boolean flag = true;
Scanner in = new Scanner(System.in);
int ch,num;
MyQueue q = new MyQueue();
while(flag)
{
System.out.println("n1.ENQUEUEn2.DEQUEUEn3.PEEKn4.DISPLAYn5.QUIT
n Enter your choice:");
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number you want to insert in queue:");
num = in.nextInt();
q.enQueue(num);
break;
case 2:
q.deQueue();
break;
case 3:
q.peek();
break;
case 4:
q.display();
break;
case 5:
flag = false;
DATA STRUCTURES USING JAVA LAB
20
203C1A0405
break;
}
}
}
Output :
C:UsersDMSSVHDesktop203C1A0405>javac Queue.java
C:UsersDMSSVHDesktop203C1A0405>java Queue
********** Queue using Array **********
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in queue:
1
1is inserted in queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in queue:
2
2is inserted in queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in queue:
3
DATA STRUCTURES USING JAVA LAB
21
203C1A0405
3is inserted in queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in queue:
4
4is inserted in queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in queue:
5
5is inserted in queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
Queue:
|1
|2
|3
|4
|5
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
2
DATA STRUCTURES USING JAVA LAB
22
203C1A0405
1is removed from Queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
Queue:
|2
|3
|4
|5
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
2
2is removed from Queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
3
the front element is:3
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
5
DATA STRUCTURES USING JAVA LAB
23
203C1A0405
4) Write a java program that reads an infix expression converts it to postfix
expression (use Stack ADT)?
import java.util.*;
import java.util.Stack;
public class InfixToPostfix
{
static int precedence(char c)
{
switch(c)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String expression)
{
String result="";
Stack<Character>stack=new Stack<>();
for(int i=0;i <expression.length();i++)
{
char c = expression.charAt(i);
if(precedence(c)>0)
{
while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c))
{
result += stack.pop();
}
stack.push(c);
DATA STRUCTURES USING JAVA LAB
24
203C1A0405
}
else
if(c==')')
{
char x = stack.pop();
while(x!='(')
{
result += x;
x = stack.pop();
}
}
else
if(c=='(')
{
stack.push(c);
}
else
{
result += c;
}
}
for(int i=0;i<=stack.size();i++)
{
result += stack.pop();
}
return result;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the expression:");
String exp = sc.nextLine();
System.out.println("Infix Expression:"+exp);
System.out.println("postfix Expression:"+infixToPostfix(exp));
}
}
DATA STRUCTURES USING JAVA LAB
25
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac InfixToPostfix.java
C:UsersDMSSVHDesktop203C1A0405>java InfixToPostfix
Enter the expression:
A+B*(C^D-E)
Infix Expression:A+B*(C^D-E)
postfix Expression:ABCD^E-*+
C:UsersDMSSVHDesktop203C1A0405>java InfixToPostfix
Enter the expression:
a+b*(c^d-e)^(f+g*h)-i
Infix Expression:a+b*(c^d-e)^(f+g*h)-i
postfix Expression:abcd^e-fgh*+^*+i-
DATA STRUCTURES USING JAVA LAB
26
203C1A0405
5) a . Write a java program to implement the following using a singly linked
List (Stack ADT) ?
import java.util.*;
class Node
{
int data;
Node next;
public Node(int data)
{
this.data=data;
this.next= null;
}
}
class Stack
{
Node top = null;
public void push(int item)
{
Node temp = new Node(item);
if(temp == null)
{
System.out.println("n stack overflow");
}
else
{
temp.data = item;
temp.next = top;
top = temp;
}
}
public boolean isEmpty()
{
return top==null;
}
public void pop()
DATA STRUCTURES USING JAVA LAB
27
203C1A0405
{
if(isEmpty())
{
System.out.println("stack underflow");
}
else
{
int x = top.data;
System.out.println("n"+x+"is removed from stack");
top = top.next;
}
}
public void peek()
{
if(isEmpty())
{
System.out.println("stack underflow");
}
else
{
System.out.println("n Top element is:"+top.data);
}
}
public void display()
{
if(isEmpty())
{
System.out.println("n stack underflow");
}
else
{
Node temp = top;
while(temp != null)
{
System.out.println("|"+temp.data);
temp = temp.next;
}
}
}
}
public class StackII
{
public static void main(String[]args)
DATA STRUCTURES USING JAVA LAB
28
203C1A0405
{
System.out.println("********** stack using Linkedlist **********");
boolean flag = true;
Scanner in = new Scanner(System.in);
int ch,num;
Stack s = new Stack();
while(flag)
{
System.out.println("n1.PUSHn2.POPn3.PEEKn4.DISPLAYn5.QUITnEnter
your choice:");
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number you want to insert in stack:");
num = in.nextInt();
s.push(num);
break;
case 2:
s.pop();
break;
case 3:
s.peek();
break;
case 4:
s.display();
break;
case 5:
flag = false;
break;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
29
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac StackII.java
C:UsersDMSSVHDesktop203C1A0405>java StackII
********** stack using Linkedlist **********
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
15
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
16
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in stack:
17
DATA STRUCTURES USING JAVA LAB
30
203C1A0405
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:1
Enter a number you want to insert in stack:
18
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
|18
|17
|16
|15
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
2
18is removed from stack
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
|17
|16
|15
1.PUSH
2.POP
DATA STRUCTURES USING JAVA LAB
31
203C1A0405
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
5
C:UsersDMSSVHDesktop203C1A0405>
5) b . Write java program to implement the following using a singly linked
List (Queue ADT) ?
import java.util.*;
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
class Queue
{
Node rear = null,front = null;
public void enqueue(int item)
{
Node temp = new Node(item);
if(temp == null)
{
System.out.println("n Queue Overflow");
}
else
{
if(front == null)
{
front = temp;
rear = temp;
}
else
{
rear.next = temp;
rear = temp;
}
DATA STRUCTURES USING JAVA LAB
32
203C1A0405
}
}
public boolean isEmpty()
{
return rear == null && front == null;
}
public void dequeue()
{
if(isEmpty())
{
System.out.println("n Queue Underflow");
}
else
{
int x = front.data;
System.out.println("n"+x+"is removed from Queue");
front = front.next;
if(front == null)
rear = null;
}
}
public void peek()
{
if(isEmpty())
{
System.out.println("n Queue Underflow");
}
else
{
System.out.println("n Front element is:"+front.data);
}
}
public void display()
{
if(isEmpty())
{
System.out.println("n Queue Underflow");
}
else
{
Node temp = front;
while(temp!=null)
{
DATA STRUCTURES USING JAVA LAB
33
203C1A0405
System.out.println("|"+temp.data);
temp = temp.next;
}
}
}
}
public class QueueII
{
public static void main(String[]args)
{
System.out.print("********** Queue using LinkedList **********");
boolean flag = true;
Scanner in = new Scanner(System.in);
int ch,num;
Queue q = new Queue();
while(flag)
{
System.out.println("n1.ENQUEUEn2.DEQUEUEn3.PEEKn4.DISPLAYn5.QUIT
n Enter your choice:");
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number you want to insert in Queue:");
num = in.nextInt();
q.enqueue(num);
break;
case 2:
q.dequeue();
break;
case 3:
q.peek();
case 4:
q.display();
break;
case 5:
flag = false;
break;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
34
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac QueueII.java
C:UsersDMSSVHDesktop203C1A0405>java QueueII
********** Queue using LinkedList **********
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
15
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
16
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
17
DATA STRUCTURES USING JAVA LAB
35
203C1A0405
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
18
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
19
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
1
Enter a number you want to insert in Queue:
20
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
4
|15
|16
|17
|18
|19
|20
DATA STRUCTURES USING JAVA LAB
36
203C1A0405
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
3
Front element is:15
|15
|16
|17
|18
|19
|20
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
2
15is removed from Queue
1.ENQUEUE
2.DEQUEUE
3.PEEK
4.DISPLAY
5.QUIT
Enter your choice:
5
C:UsersDMSSVHDesktop203C1A0405>
DATA STRUCTURES USING JAVA LAB
37
203C1A0405
6. write a java programs to implement the deque(double ended queue)ADT using
(a) // DEQUEUE USING CIRCULAR ARRAY//
import java.util.*;
class MyDeque
{
private int front=0,rear=-1,te=0;
int SIZE=10;
private int queue[]=new int[SIZE];
boolean isfull()
{
return te==SIZE;
}
boolean isempty()
{
return te==0;
}
void insertfront(int key)
{
if(isfull())
{
System.out.println("Overflow");
return;
}
if(front==0)
front=SIZE-1;
else
front=front-1;
queue[front]=key;
te++;
}
void insertrear(int key)
{
if(isfull())
{
System.out.println("Overflow");
return;
DATA STRUCTURES USING JAVA LAB
38
203C1A0405
}
rear=(rear+1)%SIZE;
queue[rear]=key;
te++;
}
void deletefront()
{
int x;
if(isempty())
{
System.out.println("Queue Underflown");
return;
}
else
{
x=queue[front];
front=(front+1)%SIZE;
System.out.println("n"+x+"is removed from front of queue");
te--;
}
}
void deleterear()
{
int x;
if(isempty())
{
System.out.println("Underflow");
return;
}
else
{
x=queue[rear];
if(rear==-1)
rear=SIZE-1;
System.out.println("n"+x+"is removed from rear of the Queue");
rear=rear-1;
te--;
}
}
int getfront()
{
if(isempty())
{
DATA STRUCTURES USING JAVA LAB
39
203C1A0405
System.out.println("Underflow");
return-1;
}
System.out.println("the front element is:"+queue[front]);
return queue[front];
}
int getrear()
{
if(isempty()||rear<0)
{
System.out.println("Underflown");
return-1;
}
System.out.println("The rear element is:"+queue[rear]);
return queue[rear];
}
void display()
{
int x,i;
if(isempty())
{
System.out.println("Underflown");
return;
}
else
{
x=front;
for(i=1;i<=te;i++)
{
System.out.println(+x+""+queue[x]);
x=(x+1)%SIZE;
}
}
}
}
class DeQue
{
public static void main(String[]args)
{
System.out.println("********** Dequeue using circular array **********");
boolean flag=true;
Scanner in=new Scanner(System.in);
DATA STRUCTURES USING JAVA LAB
40
203C1A0405
int ch,num,x;
MyDeque dq = new MyDeque();
while(flag)
{
System.out.println("n1.INSERT FRONTn2.INSERT REARn3.DELETE
FRONTn4.DELETE REARn5.GET FRONTn6.GET
REARn7.DISPLAYn8.EXITn Enter your choice:");
ch=in.nextInt();
switch(ch)
{
case 1:
System.out.print("Enter a number you want to insert in front of Dequeue:");
num = in.nextInt();
dq.insertfront(num);
break;
case 2:
System.out.print("Enter a number you want to insert in rear of Dequeue:");
num = in.nextInt();
dq.insertrear(num);
break;
case 3:
dq.deletefront();
break;
case 4:
dq.deleterear();
break;
case 5:
x=dq.getfront();
break;
case 6:
x=dq.getrear();
break;
case 7:
dq.display();
break;
case 8:
flag = false;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
41
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac DeQue.java
C:UsersDMSSVHDesktop203C1A0405>java DeQue
********** Dequeue using circular array **********
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
1
Enter a number you want to insert in front of Dequeue:15
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
1
Enter a number you want to insert in front of Dequeue:24
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
DATA STRUCTURES USING JAVA LAB
42
203C1A0405
Enter your choice:
1
Enter a number you want to insert in front of Dequeue:34
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
1
Enter a number you want to insert in front of Dequeue:44
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
1
Enter a number you want to insert in front of Dequeue:54
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
7
554
644
734
824
915
DATA STRUCTURES USING JAVA LAB
43
203C1A0405
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
2
Enter a number you want to insert in rear of Dequeue:90
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
2
Enter a number you want to insert in rear of Dequeue:80
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
2
Enter a number you want to insert in rear of Dequeue:70
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
DATA STRUCTURES USING JAVA LAB
44
203C1A0405
7.DISPLAY
8.EXIT
Enter your choice:
7
554
644
734
824
915
090
180
270
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
5
the front element is:54
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
6
The rear element is:70
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
DATA STRUCTURES USING JAVA LAB
45
203C1A0405
7.DISPLAY
8.EXIT
Enter your choice:
3
54is removed from front of queue
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
4
70is removed from rear of the Queue
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY
8.EXIT
Enter your choice:
7
644
734
824
915
090
180
1.INSERT FRONT
2.INSERT REAR
3.DELETE FRONT
4.DELETE REAR
5.GET FRONT
6.GET REAR
DATA STRUCTURES USING JAVA LAB
46
203C1A0405
7.DISPLAY
8.EXIT
Enter your choice:
6 .Write a java program to implement the deque(Double ended queue)Adt using
B) // DEQUEUE USING DOUBLY LINKED LIST//
import java.util.*;
class Dequell
{
Node front;
Node rear;
class Node
{
int i;
Node next;
Node prev;
Node(int i)
{
this.i = i;
}
}
Dequell()
{
this.front = null;
this.rear = null;
}
boolean isEmpty()
{
return front == null;
}
void insertfront(int i)
{
Node newNode = new Node(i);
if(isEmpty())
{
rear = newNode;
}
else
{
front.prev = newNode;
}
DATA STRUCTURES USING JAVA LAB
47
203C1A0405
newNode.next = front;
front = newNode;
}
void insertrear(int i)
{
Node newNode = new Node(i);
if(isEmpty())
{
front = newNode;
}
else
{
rear.next = newNode;
newNode.prev = rear;
}
rear = newNode;
}
void removefront()
{
if(isEmpty())
System.out.print("UnderFlown");
else
{
Node temp = front;
if(front.next == null)
{
rear = null;
}
else
{
front.next.prev = null;
}
front = front.next;
System.out.println("Node "+ temp.i + " deleted");
}
}
void removerear()
{
if(isEmpty())
System.out.print("UnderFlown");
else
{
Node temp = rear;
DATA STRUCTURES USING JAVA LAB
48
203C1A0405
if(rear.next == null)
{
front = null;
}
else
{
rear.prev.next = null;
}
rear = rear.prev;
System.out.println("Node "+ temp.i + " deleted");
}
}
void getfront()
{
if(isEmpty())
System.out.print("UnderFlown");
else
System.out.println("The front element is: "+front.i);
}
void getrear()
{
if(isEmpty())
System.out.print("UnderFlown");
else
System.out.println("The front element is: "+rear.i);
}
void displayforward()
{
Node current = front;
while(current != null)
{
System.out.print(current.i + " ");
current = current.next;
}
}
void displaybackward()
{
Node current = rear;
while(current != null)
{
System.out.print(current.i + " ");
current = current.prev;
DATA STRUCTURES USING JAVA LAB
49
203C1A0405
}
}
}
class Dql
{
public static void main(String[] args)
{
Dequell dq = new Dequell();
System.out.print("********** DeQueue using Doubly Linked List **********");
boolean flag=true;
Scanner in = new Scanner(System.in);
int ch, num,x;
while(flag)
{
System.out.print("n 1.INSERT FRONT n 2.INSERT REARn 3.REMOVE
FRONTn
4.REMOVE REARn 5.GET FRONTn 6.GET REARn 7.DISPLAY FORWARDn
8.DISPLAY
BACKWARD n 9.EXITnEnter your choice : ");
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.print(" Enter a number you want to insert in front of Dequeue : ");
num = in.nextInt();
dq.insertfront(num);
break;
case 2:
System.out.print(" Enter a number you want to insert in rear of Dequeue : ");
num = in.nextInt();
dq.insertrear(num);
break;
case 3:
dq.removefront();
break;
case 4:
dq.removerear();
break;
case 5:
dq.getfront();
break;
case 6:
DATA STRUCTURES USING JAVA LAB
50
203C1A0405
dq.getrear();
break;
case 7:
dq.displayforward();
break;
case 8:
dq.displaybackward();
break;
case 9:
flag=false;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
51
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac Dequell.java
C:UsersDMSSVHDesktop203C1A0405>java Dequell
********** DeQueue using Doubly Linked List **********
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 1
Enter a number you want to insert in front of Dequeue : 10
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 1
Enter a number you want to insert in front of Dequeue : 20
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
DATA STRUCTURES USING JAVA LAB
52
203C1A0405
Enter your choice : 1
Enter a number you want to insert in front of Dequeue : 30
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 7
30 20 10
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 2
Enter a number you want to insert in rear of Dequeue : 11
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 2
Enter a number you want to insert in rear of Dequeue : 22
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
DATA STRUCTURES USING JAVA LAB
53
203C1A0405
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 2
Enter a number you want to insert in rear of Dequeue : 33
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 7
30 20 10 11 22 33
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 5
The front element is: 30
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 6
The front element is: 33
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
DATA STRUCTURES USING JAVA LAB
54
203C1A0405
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice : 8
33 22 11 10 20 30
1.INSERT FRONT
2.INSERT REAR
3.REMOVE FRONT
4.REMOVE REAR
5.GET FRONT
6.GET REAR
7.DISPLAY FORWARD
8.DISPLAY BACKWARD
9. EXIT
Enter your choice :
DATA STRUCTURES USING JAVA LAB
55
203C1A0405
7.Write a java program to implement priority queue ADT?
import java.util.Scanner;
class Task
{
String job;
int priority;
public Task(String job, int priority)
{
this.job = job;
this.priority = priority;
}
public String toString()
{
return "Job Name : "+ job +"nPriority : "+ priority;
}
}
class PriQueue
{
Task[] heap;
int heapSize, capacity;
public PriQueue(int capacity)
{
this.capacity = capacity + 1;
heap = new Task[this.capacity];
heapSize = 0;
}
public void clear()
{
heap = new Task[capacity];
heapSize = 0;
}
public boolean isEmpty()
{
return heapSize == 0;
}
public boolean isFull()
{
DATA STRUCTURES USING JAVA LAB
56
203C1A0405
return heapSize == capacity - 1;
}
public int size()
{
return heapSize;
}
public void insert(String job, int priority)
{
Task newJob = new Task(job, priority);
heap[++heapSize] = newJob;
int pos = heapSize;
while (pos != 1 && newJob.priority > heap[pos/2].priority)
{
heap[pos] = heap[pos/2];
pos /=2;
}
heap[pos] = newJob;
}
public Task remove()
{
int parent, child;
Task item, temp;
item = heap[1];
temp = heap[heapSize--];
parent = 1;
child = 2;
while (child <= heapSize)
{
if (child < heapSize && heap[child].priority < heap[child + 1].priority)
child++;
if (temp.priority >= heap[child].priority)
break;
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
return item;
}
public void display()
{
int i;
DATA STRUCTURES USING JAVA LAB
57
203C1A0405
System.out.print("JobName Priorityn");
for(i=1;i<=heapSize;i++)
System.out.println( heap[i].job +" "+ heap[i].priority);
}
}
public class PriQueueTest
{
public static void main(String[] args)
{
System.out.println("********** Priority Queue **********");
boolean flag=true;
Scanner in = new Scanner(System.in);
int ch, num,x;
System.out.print("Enter size of priority queue: ");
PriQueue pq = new PriQueue(in.nextInt() );
while(flag)
{
System.out.print("n1.Insertn2.Removen3.Check Emptyn4.Check
Fulln5.Clearn6.Sizen7.Displayn8.Exit nEnter your choice :");
ch = in.nextInt();
switch(ch)
{
case 1:if(pq.isFull())
System.out.println("Priority Queue Full");
else
{
System.out.println("Enter job name and priority");
pq.insert(in.next(), in.nextInt() );
}
break;
case 2 :if(pq.isEmpty())
System.out.println("Priority Queue Empty");
else
System.out.println("nJob removed nn"+ pq.remove());
break;
case 3 :
System.out.println("nEmpty Status : "+ pq.isEmpty() );
break;
case 4 :
System.out.println("nFull Status : "+ pq.isFull() );
break;
case 5 :
DATA STRUCTURES USING JAVA LAB
58
203C1A0405
System.out.println("nPriority Queue Cleared");
pq.clear();
break;
case 6 :
System.out.println("nSize = "+ pq.size() );
break;
case 7:
pq.display();
break;
case 8:
flag=false;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
59
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac PriQueueTest.java
C:UsersDMSSVHDesktop203C1A0405>java PriQueueTest
********** Priority Queue **********
Enter size of priority queue: 3
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :1
Enter job name and priority
j1 23
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :1
Enter job name and priority
j2 56
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :1
Enter job name and priority
DATA STRUCTURES USING JAVA LAB
60
203C1A0405
j3 78
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :7
JobName Priority
j3 78
j1 23
j2 56
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :3
Empty Status : false
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :4
Full Status : true
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
DATA STRUCTURES USING JAVA LAB
61
203C1A0405
Enter your choice :6
Size = 3
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :2
Job removed
Job Name : j3
Priority : 78
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :2
Job removed
Job Name : j2
Priority : 56
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :2
Job removed
Job Name : j1
Priority : 23
1.Insert
2.Remove
3.Check Empty
4.Check Full
DATA STRUCTURES USING JAVA LAB
62
203C1A0405
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :2
Priority Queue Empty
1.Insert
2.Remove
3.Check Empty
4.Check Full
5.Clear
6.Size
7.Display
8.Exit
Enter your choice :
DATA STRUCTURES USING JAVA LAB
63
203C1A0405
8. Write Java programs that use recursive and non-recursive functions to
traverse the given binary tree in
(a) Preorder
(b) In order and
(c) Post order.
import java.util.Stack;
class Node
{
Object data;
Node left;
Node right;
Node( Object d ) // constructor
{
data = d;
}
}
class BinaryTree
{
Object tree[];
int maxSize;
Stack<Node>stk = new 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);
}
DATA STRUCTURES USING JAVA LAB
64
203C1A0405
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();
DATA STRUCTURES USING JAVA LAB
65
203C1A0405
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 )
{
DATA STRUCTURES USING JAVA LAB
66
203C1A0405
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 BinaryTreeTest
{
public static void main(String args[])
{
Object arr[] ={'A','B','C','D','E','F','G', 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);
}
}
DATA STRUCTURES USING JAVA LAB
67
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac BinaryTreeTest.java
C:UsersDMSSVHDesktop203C1A0405>java BinaryTreeTest
Recursive Binary Tree Traversals:
inorder:D B E A F C G
preorder:A B D E C F G
postorder:D E B F G C A
Non-recursive Binary Tree Traversals:
inorder:D B E A F C G
preorder:A B D E C F G
postorder:D E B F G C A
DATA STRUCTURES USING JAVA LAB
68
203C1A0405
9. Write a Java program that displays node values in a level order traversal
(Traverse the tree one level at a time, starting at the root node) for a binary tree.
import java.util.Queue;
import java.util.LinkedList;
import java.util.*;
public class Tree
{
static Node root;
static class Node
{
int data;
Node left;
Node right;
Node( int d ) // constructor
{
this.data = d;
}
}
public Node BuildTree( int arr[], int i )
{
Node root=null;
if(i&lt;arr.length)
{
root=new Node(arr[i]);
root.left=BuildTree(arr,2*i+1);
root.right = BuildTree(arr,2*i+2);
}
return root;
}
public void printLevelOrder(Node root)
{
Queue&lt;Node&gt; queue = new LinkedList&lt;Node&gt;();
queue.add(root);
while (!queue.isEmpty()) {
Node tempNode = queue.poll();
System.out.print(tempNode.data + &quot; &quot;);
if (tempNode.left != null) {
DATA STRUCTURES USING JAVA LAB
69
203C1A0405
queue.add(tempNode.left);
}
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
public void inorder(Node p)
{
if( p != null )
{
inorder(p.left);
System.out.print(p.data + &quot; &quot;);
inorder(p.right);
}
}
public static void main(String args[])
{
Tree t=new Tree();
int[] arr=new int[6];
Scanner in = new Scanner(System.in);
int i;
for(i=0;i&lt;=5;i++)
arr[i]=in.nextInt();
t.root=t.BuildTree(arr,0);
System.out.print(&quot;n Level Order Traversal: &quot;);
t.printLevelOrder(root);
System.out.print(&quot;n InOrder Traversal: &quot;);
t.inorder(root);
}
}
DATA STRUCTURES USING JAVA LAB
70
203C1A0405
OUTPUT:
C:UsersDMSSVHDesktop203C1A0405>javac Tree.java
C:UsersDMSSVHDesktop203C1A0405>java Tree
1 2 3 4 5 6
Level Order Traversal: 1 2 3 4 5 6
InOrder Traversal: 4 2 5 1 6 3
DATA STRUCTURES USING JAVA LAB
71
203C1A0405
10. Write a Java program that uses recursive functions.
(a) To create a binary search tree.
(b) To count the number of leaf nodes.
(c) To copy the above binary search tree.
import java.util.*;
class Node
{
int data;
Node left, right;
Node(int key)
{
data = key;
left = right = null;
}
}
class BST
{
public static void inorder(Node root)
{
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + &quot; &quot;);
inorder(root.right);
}
public static Node insert(Node root, int key)
{
if (root == null)
{
return new Node(key);
}
if (key &lt; root.data)
{
DATA STRUCTURES USING JAVA LAB
72
203C1A0405
root.left = insert(root.left, key);
}
else
{
root.right = insert(root.right, key);
}
return root;
}
int getLeafCount(Node node)
{
if (node == null)
return 0;
if (node.left == null &amp;&amp; node.right == null)
return 1;
else
return getLeafCount(node.left) + getLeafCount(node.right);
}
Node cloneBST(Node root)
{
if (root == null)
{
return null;
}
Node root_copy = new Node(root.data);
root_copy.left = cloneBST(root.left);
root_copy.right = cloneBST(root.right);
return root_copy;
}
}
class BSTMain
{
public static void main(String[] args)
{
int key;
boolean flag=true;
Scanner in = new Scanner(System.in);
int ch, n;
Node root=null,root_copy=null;;
BST b=new BST();
while(flag)
{
System.out.print(&quot;n1.Create BSTn2.Count Leavesn3.Copy Treen4.Inorder
DATA STRUCTURES USING JAVA LAB
73
203C1A0405
traversaln5.ExitnEnter your Choice: &quot;);
ch = in.nextInt();
switch(ch)
{
case 1:
System.out.print(&quot;nEnter the number of keys:&quot;);
n=in.nextInt();
System.out.println(&quot;nEnter &quot;+n+&quot; Keys:&quot;);
for(int i=1;i&lt;=n;i++)
{
key=in.nextInt();
root=b.insert(root,key);
}
break;
case 2: System.out.print(&quot;Number of leaf nodes: &quot;+b.getLeafCount(root));
break;
case 3: root_copy=b.cloneBST(root);
System.out.println(&quot;BST is copied,New Tree Inorder traversal:n&quot;);
b.inorder(root_copy);
break;
case 4: b.inorder(root);
break;
case 5: flag=false;
}
}
}
}
DATA STRUCTURES USING JAVA LAB
74
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac BSTMain.java
C:UsersDMSSVHDesktop203C1A0405>java BSTMain
1.Create BST
2.Count Leaves
3.Copy Tree
4.Inorder traversal
5.Exit
Enter your Choice: 1
Enter the number of keys:6
Enter 6 Keys:
50 70 80 15 30 68
1.Create BST
2.Count Leaves
3.Copy Tree
4.Inorder traversal
5.Exit
Enter your Choice: 2
Number of leaf nodes: 3
1.Create BST
2.Count Leaves
3.Copy Tree
4.Inorder traversal
5.Exit
Enter your Choice: 4
15 30 50 68 70 80
1.Create BST
2.Count Leaves
3.Copy Tree
4.Inorder traversal
5.Exit
DATA STRUCTURES USING JAVA LAB
75
203C1A0405
Enter your Choice: 3
BST is copied,New Tree Inorder traversal:
15 30 50 68 70 80
1.Create BST
2.Count Leaves
3.Copy Tree
4.Inorder traversal
5.Exit
Enter your Choice: 5
DATA STRUCTURES USING JAVA LAB
76
203C1A0405
11. Write Java programs for the implementation of bfs and dfs for a given
graph?
import java.util.*;
class GTraversal
{
int N;
int [][]adj;
int[] visited;
LinkedList<Integer> q=new LinkedList<Integer>();
GTraversal(int n)
{
N=n;
adj=new int[N][N];
visited=new int[N];
for(int i=0;i<N;i++)
visited[i]=0;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
adj[i][j]=0;
}
void addEdge(int u,int v)
{
adj[u][v]=1;
adj[v][u]=1;
}
public void printMatrix()
{
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
System.out.print(+adj[i][j]+" ");
DATA STRUCTURES USING JAVA LAB
77
203C1A0405
}
System.out.print("n");
}
}
void BFS(int s)
{
q.add(s);
visited[s]=1;
while(!q.isEmpty())
{
int x=q.poll();
System.out.print(x+" ");
for(int i=0;i<N;i++)
{
if(adj[x][i]==1 && (visited[i]==0))
{
q.add(i);
visited[i]=1;
}
}
}
}
void DFS(int s)
{
int j;
System.out.print(s+" ");
visited[s]=1;
for(j=0;j<N;j++)
if(visited[j]==0&&adj[s][j]==1)
DFS(j);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num,e,u,v;
System.out.println("Enter the number of vertices:");
num=in.nextInt();
GTraversal g=new GTraversal(num);
GTraversal g1=new GTraversal(num);
System.out.println("Enter the Number of Edges:");
DATA STRUCTURES USING JAVA LAB
78
203C1A0405
e=in.nextInt();
System.out.println("Enter the Edges:");
for(int i=1;i<=e;i++)
{
u=in.nextInt();
v=in.nextInt();
g.addEdge(u,v);
g1.addEdge(u,v);
}
g.printMatrix();
System.out.println("BFS");
g.BFS(0);
System.out.println("nDFS");
g1.DFS(0);
}
}
DATA STRUCTURES USING JAVA LAB
79
203C1A0405
Output:
C:UsersstaffDesktopJAVA>java GTraversal
Enter the number of vertices:
7
Enter the Number of Edges:
11
Enter the Edges:
0 1
0 3
1 3
1 2
2 3
2 4
2 5
3 4
4 6
6 1
1 5
0 1 0 1 0 0 0
1 0 1 1 0 1 1
0 1 0 1 1 1 0
1 1 1 0 1 0 0
0 0 1 1 0 0 1
0 1 1 0 0 0 0
0 1 0 0 1 0 0
BFS
0 1 3 2 5 6 4
DFS
0 1 2 3 4 6 5
DATA STRUCTURES USING JAVA LAB
80
203C1A0405
12 . write java program for implementing the following sorting methods:
a) Bubble sort
import java.util.*;
class BubbleSort
{
void BubbleSort(int arr[],int n)
{
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(arr[j]>arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
void printArray(int arr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[]args)
{
BubbleSort ob = new BubbleSort();
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
n=sc.nextInt();
int[]arr=new int[n];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
DATA STRUCTURES USING JAVA LAB
81
203C1A0405
ob.BubbleSort(arr,n);
System.out.println("Sorted array-BubbleSort");
ob.printArray(arr);
}
}
Output :
C:UsersDMSSVHDesktop203C1A0405>javac BubbleSort.java
C:UsersDMSSVHDesktop203C1A0405>java BubbleSort
Enter the number of elements:5
Enter the elements of the array:
10
20
30
40
50
Sorted array-BubbleSort
10 20 30 40 50
DATA STRUCTURES USING JAVA LAB
82
203C1A0405
b) Selection Sort
import java.util.*;
class SelectionSort
{
void SelectionSort(int arr[],int n)
{
int k,pos,temp;
for(k=0;k<n;k++)
{
pos = smallest(arr,k,n);
temp = arr[k];
arr[k] = arr[pos];
arr[pos] = temp;
}
}
int smallest(int arr[],int k,int n)
{
int pos = k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void printArray(int arr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[]args)
DATA STRUCTURES USING JAVA LAB
83
203C1A0405
{
SelectionSort s = new SelectionSort();
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
n=sc.nextInt();
int[]arr=new int[n];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
s.SelectionSort(arr,n);
System.out.println("Sorted array-SelectionSort");
s.printArray(arr);
}
}
DATA STRUCTURES USING JAVA LAB
84
203C1A0405
Output :
C:UsersDMSSVHDesktop203C1A0405>javac SelectionSort.java
C:UsersDMSSVHDesktop203C1A0405>java SelectionSort
Enter the number of elements:5
Enter the elements of the array:
21
22
23
24
25
Sorted array-SelectionSort
21 22 23 24 25
DATA STRUCTURES USING JAVA LAB
85
203C1A0405
C) Insert Sort
import java.util.*;
public class InsertSort
{
void InsertSort(int arr[])
{
int n = arr.length;
for(int i=1;i<n;i++)
{
int key = arr[i];
int j=i-1;
while(j>=0&&arr[j]>key)
{
arr[j+1]=arr[j];
j = j-1;
}
arr[j+1]=key;
}
}
void printArray(int arr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[]args)
{
SelectionSort s = new SelectionSort();
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements:");
n=sc.nextInt();
int[]arr1=new int[n];
System.out.println("Enter the elements of the array:");
for(int i=0;i<n;i++)
{
DATA STRUCTURES USING JAVA LAB
86
203C1A0405
arr1[i]=sc.nextInt();
}
InsertSort ob = new InsertSort();
ob.InsertSort(arr1);
ob.printArray(arr1)
}}
Output :
C:UsersDMSSVHDesktop203C1A0405>javac InsertSort.java
C:UsersDMSSVHDesktop203C1A0405>java InsertSort
Enter the number of elements:5
Enter the elements of the array:
71
72
73
74
75
71 72 73 74 75
DATA STRUCTURES USING JAVA LAB
87
203C1A0405
13. Write a Java program for implementing KMP pattern matching algorithm.
import java.util.*;
class KMP
{
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
int lps[] = new int[M];
int j = 0;
computeLPSArray(pat, M, lps);
int i = 0;
while ((N - i) >= (M - j))
{
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];
}
else
if (i < N && pat.charAt(j) != txt.charAt(i))
{
if (j != 0)
j = lps[j - 1];
else
DATA STRUCTURES USING JAVA LAB
88
203C1A0405
i = i + 1;
}
}
}
void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M)
{
if (pat.charAt(i) == pat.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0)
{
len = lps[len - 1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
}
public static void main(String args[])
{
String txt,pat;
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
txt=sc.nextLine();
System.out.print("enter the pattern string: ");
pat=sc.nextLine();
DATA STRUCTURES USING JAVA LAB
89
203C1A0405
new KMP().kmpSearch(pat,str);
}
}
Output :
C:UsersDMSSVHDesktop203C1A0405>javac KMP.java
C:UsersDMSSVHDesktop203C1A0405>java KMP
Enter a string: sushmasushmasushma
enter the pattern string: ma
Found pattern at index 4
Found pattern at index 10
Found pattern at index 16
C:UsersDMSSVHDesktop203C1A0405>javac KMP.java
C:UsersDMSSVHDesktop203C1A0405>java KMP
Enter a string: heyhiheyheyhi
enter the pattern string: he
Found pattern at index 0
Found pattern at index 5
Found pattern at index 8

More Related Content

PDF
CS3381 OBJECT ORIENTED PROGRAMMINGLABS_1.pdf
DOCX
object oriented programming lab manual .docx
DOCX
cs3381-object oriented programming-ab-manual
DOCX
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
PPTX
array lecture engineeringinformatin_technology.pptx
DOCX
611+tutorial
PDF
Data structures lab manual
DOCX
QA Auotmation Java programs,theory
CS3381 OBJECT ORIENTED PROGRAMMINGLABS_1.pdf
object oriented programming lab manual .docx
cs3381-object oriented programming-ab-manual
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
array lecture engineeringinformatin_technology.pptx
611+tutorial
Data structures lab manual
QA Auotmation Java programs,theory

Similar to DS LAB RECORD.docx (20)

DOC
Ds lab manual by s.k.rath
DOCX
Binary search
PDF
Save Write a program to implement Binary search using recursive algo.pdf
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
PDF
Refer to my progress on this assignment belowIn this problem you w.pdf
PDF
Java Assignment.Implement a binary search algorithm on an array..pdf
DOCX
Data structure
PDF
Data Structure.pdf
PDF
Aj unit2 notesjavadatastructures
PDF
Data Structures Notes 2021
PPTX
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
PDF
Java Algorithm Interview Questions & Answers .pdf
DOC
(Cse cs) ads programs list
PDF
Computer java programs
PDF
Functional data structures
PPT
2 b queues
PDF
4. The size of instructions can be fixed or variable. What are advant.pdf
DOCX
Data structure and algorithm lab spiral (1) (4) (1).docx
PDF
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
PPTX
Arrays.pptx
Ds lab manual by s.k.rath
Binary search
Save Write a program to implement Binary search using recursive algo.pdf
package DataStructures; public class HelloWorld AnyType extends.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
Java Assignment.Implement a binary search algorithm on an array..pdf
Data structure
Data Structure.pdf
Aj unit2 notesjavadatastructures
Data Structures Notes 2021
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
Java Algorithm Interview Questions & Answers .pdf
(Cse cs) ads programs list
Computer java programs
Functional data structures
2 b queues
4. The size of instructions can be fixed or variable. What are advant.pdf
Data structure and algorithm lab spiral (1) (4) (1).docx
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Arrays.pptx
Ad

Recently uploaded (20)

PPTX
communication and presentation skills 01
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
737-MAX_SRG.pdf student reference guides
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PPTX
Management Information system : MIS-e-Business Systems.pptx
PDF
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
PDF
distributed database system" (DDBS) is often used to refer to both the distri...
PDF
Design Guidelines and solutions for Plastics parts
PPTX
Fundamentals of Mechanical Engineering.pptx
PPTX
CyberSecurity Mobile and Wireless Devices
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PDF
Visual Aids for Exploratory Data Analysis.pdf
PPTX
Information Storage and Retrieval Techniques Unit III
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PPTX
Current and future trends in Computer Vision.pptx
PDF
Abrasive, erosive and cavitation wear.pdf
communication and presentation skills 01
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
Fundamentals of safety and accident prevention -final (1).pptx
737-MAX_SRG.pdf student reference guides
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
August 2025 - Top 10 Read Articles in Network Security & Its Applications
Management Information system : MIS-e-Business Systems.pptx
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
distributed database system" (DDBS) is often used to refer to both the distri...
Design Guidelines and solutions for Plastics parts
Fundamentals of Mechanical Engineering.pptx
CyberSecurity Mobile and Wireless Devices
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
Visual Aids for Exploratory Data Analysis.pdf
Information Storage and Retrieval Techniques Unit III
"Array and Linked List in Data Structures with Types, Operations, Implementat...
III.4.1.2_The_Space_Environment.p pdffdf
Current and future trends in Computer Vision.pptx
Abrasive, erosive and cavitation wear.pdf
Ad

DS LAB RECORD.docx

  • 1. DATA STRUCTURES USING JAVA LAB 1 203C1A0405 1a) i.write java program that use non –recursive function for implementation linear search? import java.util.Scanner; class NrLinear { public static void main(String[]args) { int n,key; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements:"); n = sc.nextInt(); int[]arr = new int[10]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } System.out.println("Enter the key element:"); key = sc.nextInt(); int result = search(arr,n,key); if(result == -1) System.out.print("Element is not present in array"); else System.out.print("Element is present at index"+(result)); } public static int search(int arr[],int n,int key) { for(int i=0;i<n;i++) { if (arr[i]==key) return i; } return-1; } }
  • 2. DATA STRUCTURES USING JAVA LAB 2 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac NrLinear.java C:UsersDMSSVHDesktop203C1A0405>java NrLinear Enter the number of elements:5 Enter the elements of the array: 1 2 3 4 5 Enter the key element: 4 Element is present at index3
  • 3. DATA STRUCTURES USING JAVA LAB 3 203C1A0405 1a) ii .write java program that use recursive function for implementation linear search? import java.util.Scanner; class RLinear { public static void main(String[]args) { int n,key; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements:"); n = sc.nextInt(); int[]arr = new int[10]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) {arr[i] = sc.nextInt(); } System.out.println("Enter the key element:"); key = sc.nextInt(); int result = search(arr,n,key); if(result == -1) System.out.print("Element is not present in array"); else System.out.print("Element is present at index"+(result)); } public static int search(int arr[],int n,int key) { n--; if(n<0) return-1; if(arr[n]==key) return n; else return search(arr,n,key); } }
  • 4. DATA STRUCTURES USING JAVA LAB 4 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac RLinear.java C:UsersDMSSVHDesktop203C1A0405>java RLinear Enter the number of elements:5 Enter the elements of the array: 10 20 30 40 50 Enter the key element: 50 Element is present at index4
  • 5. DATA STRUCTURES USING JAVA LAB 5 203C1A0405 1b) i. Write java program that use a non-recursive function for implementing Binary search? import java.util.Scanner; class NrBinary { public static void main(String[]args) { int n,key; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements:"); n = sc.nextInt(); int[] arr = new int[10]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } System.out.println("Enter the key element:"); key = sc.nextInt(); sort(arr,n); System.out.println("The sorted elements are:"); for(int i=0;i<n;i++) System.out.print(arr[i]+ " "); System.out.println(); int result = binarySearch(arr,0,n-1,key); if(result == -1) System.out.print("Elements is not present in array"); else System.out.print("Element is present at index" +(result+1)); } public static int binarySearch(int arr[], int l, int r, int x) { while(l <= r) { int mid = (l+r)/2; if(arr[mid] == x) return mid;
  • 6. DATA STRUCTURES USING JAVA LAB 6 203C1A0405 if(arr[mid] > x) r = mid-1; else if(arr[mid] < x) l = mid+1; } return -1; } public static void sort(int arr[],int n) { for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } }
  • 7. DATA STRUCTURES USING JAVA LAB 7 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac NrBinary.java C:UsersDMSSVHDesktop203C1A0405>java NrBinary Enter the number of elements: 5 Enter the elements of the array: 3 6 1 8 7 Enter the key element: 8 The sorted elements are: 1 3 6 7 8 Element is present at index5
  • 8. DATA STRUCTURES USING JAVA LAB 8 203C1A0405 1b) ii. Write java program that use a Recursive function for implementing Binary search? import java.util.Scanner; class RBinary { public static void main(String[]args) { int n,key; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements:"); n = sc.nextInt(); int[]arr = new int[10]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } System.out.println("Enter the key element:"); key = sc.nextInt(); sort(arr,n); System.out.println("The sorted elements are:"); for(int i=0;i<n;i++) System.out.print(arr[i]+ " "); System.out.println(); int result = binarySearch(arr,0,n-1,key); if(result == -1) System.out.println("Element is not present in array"); else System.out.println("Element is present at index" +(result+1)); } public static int binarySearch(int arr[],int l,int x,int r) { if(l <= r) { int mid = (1+r)/2; if(arr[mid] == x)
  • 9. DATA STRUCTURES USING JAVA LAB 9 203C1A0405 return mid; if(arr[mid] > x) return binarySearch(arr,l,mid-1,x); if(arr[mid] < x) return binarySearch(arr,mid+1,r,x); } return-1; } public static void sort(int arr[],int n) { for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } }
  • 10. DATA STRUCTURES USING JAVA LAB 10 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac RBinary.java C:UsersDMSSVHDesktop203C1A0405>java RBinary Enter the number of elements: 5 Enter the elements of the array: 4 3 6 2 1 Enter the key element: 6 The sorted elements are: 1 2 3 4 6 Element is present at index4
  • 11. DATA STRUCTURES USING JAVA LAB 11 203C1A0405 3) Write a java programs to implement the following using an array? a) Stack ADT import java.util.*; class MyStack { private int top = -1; int SIZE = 5; private int stk[] = new int[SIZE]; boolean isFull() { if(top == SIZE-1) return true; else return false; } boolean isEmpty() { if(top == -1) return true; else return false; } void push(int num) { if(isFull()) { System.out.println("Stack Overflow"); } else { stk[++top] = num; System.out.println("n"+num+"is inserted in stack"); } } int pop() { if(isEmpty())
  • 12. DATA STRUCTURES USING JAVA LAB 12 203C1A0405 { System.out.println("n Stack Underflow"); return 0; } else { int x = stk[top]; top--; System.out.println("n"+x+"is removed from stack"); return x; } } int peek() { if(isEmpty()) { System.out.println("n Stack Underflow"); return 0; } else { System.out.println("the top element is:"+stk[top]); return stk[top]; } } void display() { if(isEmpty()) { System.out.println("n Stack Empty"); } else { System.out.println("n Stack:"); for(int i=0;i<=top;i++) { System.out.println("|"+stk[i]); } } } } class Stack {
  • 13. DATA STRUCTURES USING JAVA LAB 13 203C1A0405 public static void main(String[]args) { System.out.println("********** stack using Array **********"); boolean flag = true; Scanner in = new Scanner(System.in); int ch,num; MyStack s = new MyStack(); while(flag) { System.out.println("n1.PUSHn2.POPn3.PEEKn4.DISPLAYn5.QUITn Enter your choice:"); ch = in.nextInt(); switch(ch) { case 1: System.out.println("Enter a number you want to insert in stack:"); num = in.nextInt(); s.push(num); break; case 2: s.pop(); break; case 3: s.peek(); break; case 4: s.display(); break; case 5: flag = false; break; } } } }
  • 14. DATA STRUCTURES USING JAVA LAB 14 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac Stack.java C:UsersDMSSVHDesktop203C1A0405>java Stack ********** stack using Array ********** 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 1 1is inserted in stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 2 2is inserted in stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 3
  • 15. DATA STRUCTURES USING JAVA LAB 15 203C1A0405 3is inserted in stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 4 4is inserted in stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 5 5is inserted in stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 Stack: |1 |2 |3 |4 |5 1.PUSH
  • 16. DATA STRUCTURES USING JAVA LAB 16 203C1A0405 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 2 5is removed from stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 3 the top element is:4 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice:5
  • 17. DATA STRUCTURES USING JAVA LAB 17 203C1A0405 3) b . Write a java programs to implement the following using an array? ( Queue ADT) import java.util.*; class MyQueue { private int front = -1,rear = -1; int SIZE = 5; private int queue[] = new int[SIZE]; boolean isFull() { if(front == 0&&rear == SIZE-1) return true; else return false; } boolean isEmpty() { if(front == -1) return true; else return false; } void enQueue(int num) { if(isFull()) { System.out.println("Queue Overflow"); } else { if(front == -1) { front = 0; } rear++; queue[rear] = num;
  • 18. DATA STRUCTURES USING JAVA LAB 18 203C1A0405 System.out.println("n"+num+"is inserted in queue"); } } int deQueue() { int x; if(isEmpty()) { System.out.println("n Queue Underflow"); return 0; } else { x = queue[front]; front++; if(front >= rear) { front = -1; rear = -1; } System.out.println("n"+x+"is removed from Queue"); return x; } } int peek() { if(isEmpty()) { System.out.println("n Queue Underflow"); return 0; } else { System.out.println("the front element is:"+queue[front]); return queue[front]; } } void display() { if(isEmpty()) { System.out.println("n Queue Empty"); }
  • 19. DATA STRUCTURES USING JAVA LAB 19 203C1A0405 else { System.out.println("n Queue:"); for(int i=front;i<=rear;i++) { System.out.println("|"+queue[i]); } } } } class Queue { public static void main(String[]args) { System.out.println("********** Queue using Array **********"); boolean flag = true; Scanner in = new Scanner(System.in); int ch,num; MyQueue q = new MyQueue(); while(flag) { System.out.println("n1.ENQUEUEn2.DEQUEUEn3.PEEKn4.DISPLAYn5.QUIT n Enter your choice:"); ch = in.nextInt(); switch(ch) { case 1: System.out.println("Enter a number you want to insert in queue:"); num = in.nextInt(); q.enQueue(num); break; case 2: q.deQueue(); break; case 3: q.peek(); break; case 4: q.display(); break; case 5: flag = false;
  • 20. DATA STRUCTURES USING JAVA LAB 20 203C1A0405 break; } } } Output : C:UsersDMSSVHDesktop203C1A0405>javac Queue.java C:UsersDMSSVHDesktop203C1A0405>java Queue ********** Queue using Array ********** 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in queue: 1 1is inserted in queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in queue: 2 2is inserted in queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in queue: 3
  • 21. DATA STRUCTURES USING JAVA LAB 21 203C1A0405 3is inserted in queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in queue: 4 4is inserted in queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in queue: 5 5is inserted in queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 Queue: |1 |2 |3 |4 |5 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 2
  • 22. DATA STRUCTURES USING JAVA LAB 22 203C1A0405 1is removed from Queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 Queue: |2 |3 |4 |5 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 2 2is removed from Queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 3 the front element is:3 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 5
  • 23. DATA STRUCTURES USING JAVA LAB 23 203C1A0405 4) Write a java program that reads an infix expression converts it to postfix expression (use Stack ADT)? import java.util.*; import java.util.Stack; public class InfixToPostfix { static int precedence(char c) { switch(c) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } static String infixToPostfix(String expression) { String result=""; Stack<Character>stack=new Stack<>(); for(int i=0;i <expression.length();i++) { char c = expression.charAt(i); if(precedence(c)>0) { while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c)) { result += stack.pop(); } stack.push(c);
  • 24. DATA STRUCTURES USING JAVA LAB 24 203C1A0405 } else if(c==')') { char x = stack.pop(); while(x!='(') { result += x; x = stack.pop(); } } else if(c=='(') { stack.push(c); } else { result += c; } } for(int i=0;i<=stack.size();i++) { result += stack.pop(); } return result; } public static void main(String[]args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the expression:"); String exp = sc.nextLine(); System.out.println("Infix Expression:"+exp); System.out.println("postfix Expression:"+infixToPostfix(exp)); } }
  • 25. DATA STRUCTURES USING JAVA LAB 25 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac InfixToPostfix.java C:UsersDMSSVHDesktop203C1A0405>java InfixToPostfix Enter the expression: A+B*(C^D-E) Infix Expression:A+B*(C^D-E) postfix Expression:ABCD^E-*+ C:UsersDMSSVHDesktop203C1A0405>java InfixToPostfix Enter the expression: a+b*(c^d-e)^(f+g*h)-i Infix Expression:a+b*(c^d-e)^(f+g*h)-i postfix Expression:abcd^e-fgh*+^*+i-
  • 26. DATA STRUCTURES USING JAVA LAB 26 203C1A0405 5) a . Write a java program to implement the following using a singly linked List (Stack ADT) ? import java.util.*; class Node { int data; Node next; public Node(int data) { this.data=data; this.next= null; } } class Stack { Node top = null; public void push(int item) { Node temp = new Node(item); if(temp == null) { System.out.println("n stack overflow"); } else { temp.data = item; temp.next = top; top = temp; } } public boolean isEmpty() { return top==null; } public void pop()
  • 27. DATA STRUCTURES USING JAVA LAB 27 203C1A0405 { if(isEmpty()) { System.out.println("stack underflow"); } else { int x = top.data; System.out.println("n"+x+"is removed from stack"); top = top.next; } } public void peek() { if(isEmpty()) { System.out.println("stack underflow"); } else { System.out.println("n Top element is:"+top.data); } } public void display() { if(isEmpty()) { System.out.println("n stack underflow"); } else { Node temp = top; while(temp != null) { System.out.println("|"+temp.data); temp = temp.next; } } } } public class StackII { public static void main(String[]args)
  • 28. DATA STRUCTURES USING JAVA LAB 28 203C1A0405 { System.out.println("********** stack using Linkedlist **********"); boolean flag = true; Scanner in = new Scanner(System.in); int ch,num; Stack s = new Stack(); while(flag) { System.out.println("n1.PUSHn2.POPn3.PEEKn4.DISPLAYn5.QUITnEnter your choice:"); ch = in.nextInt(); switch(ch) { case 1: System.out.println("Enter a number you want to insert in stack:"); num = in.nextInt(); s.push(num); break; case 2: s.pop(); break; case 3: s.peek(); break; case 4: s.display(); break; case 5: flag = false; break; } } } }
  • 29. DATA STRUCTURES USING JAVA LAB 29 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac StackII.java C:UsersDMSSVHDesktop203C1A0405>java StackII ********** stack using Linkedlist ********** 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 15 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 16 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in stack: 17
  • 30. DATA STRUCTURES USING JAVA LAB 30 203C1A0405 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice:1 Enter a number you want to insert in stack: 18 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 |18 |17 |16 |15 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 2 18is removed from stack 1.PUSH 2.POP 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 |17 |16 |15 1.PUSH 2.POP
  • 31. DATA STRUCTURES USING JAVA LAB 31 203C1A0405 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 5 C:UsersDMSSVHDesktop203C1A0405> 5) b . Write java program to implement the following using a singly linked List (Queue ADT) ? import java.util.*; class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } class Queue { Node rear = null,front = null; public void enqueue(int item) { Node temp = new Node(item); if(temp == null) { System.out.println("n Queue Overflow"); } else { if(front == null) { front = temp; rear = temp; } else { rear.next = temp; rear = temp; }
  • 32. DATA STRUCTURES USING JAVA LAB 32 203C1A0405 } } public boolean isEmpty() { return rear == null && front == null; } public void dequeue() { if(isEmpty()) { System.out.println("n Queue Underflow"); } else { int x = front.data; System.out.println("n"+x+"is removed from Queue"); front = front.next; if(front == null) rear = null; } } public void peek() { if(isEmpty()) { System.out.println("n Queue Underflow"); } else { System.out.println("n Front element is:"+front.data); } } public void display() { if(isEmpty()) { System.out.println("n Queue Underflow"); } else { Node temp = front; while(temp!=null) {
  • 33. DATA STRUCTURES USING JAVA LAB 33 203C1A0405 System.out.println("|"+temp.data); temp = temp.next; } } } } public class QueueII { public static void main(String[]args) { System.out.print("********** Queue using LinkedList **********"); boolean flag = true; Scanner in = new Scanner(System.in); int ch,num; Queue q = new Queue(); while(flag) { System.out.println("n1.ENQUEUEn2.DEQUEUEn3.PEEKn4.DISPLAYn5.QUIT n Enter your choice:"); ch = in.nextInt(); switch(ch) { case 1: System.out.println("Enter a number you want to insert in Queue:"); num = in.nextInt(); q.enqueue(num); break; case 2: q.dequeue(); break; case 3: q.peek(); case 4: q.display(); break; case 5: flag = false; break; } } } }
  • 34. DATA STRUCTURES USING JAVA LAB 34 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac QueueII.java C:UsersDMSSVHDesktop203C1A0405>java QueueII ********** Queue using LinkedList ********** 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 15 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 16 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 17
  • 35. DATA STRUCTURES USING JAVA LAB 35 203C1A0405 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 18 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 19 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 1 Enter a number you want to insert in Queue: 20 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 4 |15 |16 |17 |18 |19 |20
  • 36. DATA STRUCTURES USING JAVA LAB 36 203C1A0405 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 3 Front element is:15 |15 |16 |17 |18 |19 |20 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 2 15is removed from Queue 1.ENQUEUE 2.DEQUEUE 3.PEEK 4.DISPLAY 5.QUIT Enter your choice: 5 C:UsersDMSSVHDesktop203C1A0405>
  • 37. DATA STRUCTURES USING JAVA LAB 37 203C1A0405 6. write a java programs to implement the deque(double ended queue)ADT using (a) // DEQUEUE USING CIRCULAR ARRAY// import java.util.*; class MyDeque { private int front=0,rear=-1,te=0; int SIZE=10; private int queue[]=new int[SIZE]; boolean isfull() { return te==SIZE; } boolean isempty() { return te==0; } void insertfront(int key) { if(isfull()) { System.out.println("Overflow"); return; } if(front==0) front=SIZE-1; else front=front-1; queue[front]=key; te++; } void insertrear(int key) { if(isfull()) { System.out.println("Overflow"); return;
  • 38. DATA STRUCTURES USING JAVA LAB 38 203C1A0405 } rear=(rear+1)%SIZE; queue[rear]=key; te++; } void deletefront() { int x; if(isempty()) { System.out.println("Queue Underflown"); return; } else { x=queue[front]; front=(front+1)%SIZE; System.out.println("n"+x+"is removed from front of queue"); te--; } } void deleterear() { int x; if(isempty()) { System.out.println("Underflow"); return; } else { x=queue[rear]; if(rear==-1) rear=SIZE-1; System.out.println("n"+x+"is removed from rear of the Queue"); rear=rear-1; te--; } } int getfront() { if(isempty()) {
  • 39. DATA STRUCTURES USING JAVA LAB 39 203C1A0405 System.out.println("Underflow"); return-1; } System.out.println("the front element is:"+queue[front]); return queue[front]; } int getrear() { if(isempty()||rear<0) { System.out.println("Underflown"); return-1; } System.out.println("The rear element is:"+queue[rear]); return queue[rear]; } void display() { int x,i; if(isempty()) { System.out.println("Underflown"); return; } else { x=front; for(i=1;i<=te;i++) { System.out.println(+x+""+queue[x]); x=(x+1)%SIZE; } } } } class DeQue { public static void main(String[]args) { System.out.println("********** Dequeue using circular array **********"); boolean flag=true; Scanner in=new Scanner(System.in);
  • 40. DATA STRUCTURES USING JAVA LAB 40 203C1A0405 int ch,num,x; MyDeque dq = new MyDeque(); while(flag) { System.out.println("n1.INSERT FRONTn2.INSERT REARn3.DELETE FRONTn4.DELETE REARn5.GET FRONTn6.GET REARn7.DISPLAYn8.EXITn Enter your choice:"); ch=in.nextInt(); switch(ch) { case 1: System.out.print("Enter a number you want to insert in front of Dequeue:"); num = in.nextInt(); dq.insertfront(num); break; case 2: System.out.print("Enter a number you want to insert in rear of Dequeue:"); num = in.nextInt(); dq.insertrear(num); break; case 3: dq.deletefront(); break; case 4: dq.deleterear(); break; case 5: x=dq.getfront(); break; case 6: x=dq.getrear(); break; case 7: dq.display(); break; case 8: flag = false; } } } }
  • 41. DATA STRUCTURES USING JAVA LAB 41 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac DeQue.java C:UsersDMSSVHDesktop203C1A0405>java DeQue ********** Dequeue using circular array ********** 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 1 Enter a number you want to insert in front of Dequeue:15 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 1 Enter a number you want to insert in front of Dequeue:24 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT
  • 42. DATA STRUCTURES USING JAVA LAB 42 203C1A0405 Enter your choice: 1 Enter a number you want to insert in front of Dequeue:34 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 1 Enter a number you want to insert in front of Dequeue:44 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 1 Enter a number you want to insert in front of Dequeue:54 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 7 554 644 734 824 915
  • 43. DATA STRUCTURES USING JAVA LAB 43 203C1A0405 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 2 Enter a number you want to insert in rear of Dequeue:90 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 2 Enter a number you want to insert in rear of Dequeue:80 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 2 Enter a number you want to insert in rear of Dequeue:70 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR
  • 44. DATA STRUCTURES USING JAVA LAB 44 203C1A0405 7.DISPLAY 8.EXIT Enter your choice: 7 554 644 734 824 915 090 180 270 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 5 the front element is:54 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 6 The rear element is:70 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR
  • 45. DATA STRUCTURES USING JAVA LAB 45 203C1A0405 7.DISPLAY 8.EXIT Enter your choice: 3 54is removed from front of queue 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 4 70is removed from rear of the Queue 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY 8.EXIT Enter your choice: 7 644 734 824 915 090 180 1.INSERT FRONT 2.INSERT REAR 3.DELETE FRONT 4.DELETE REAR 5.GET FRONT 6.GET REAR
  • 46. DATA STRUCTURES USING JAVA LAB 46 203C1A0405 7.DISPLAY 8.EXIT Enter your choice: 6 .Write a java program to implement the deque(Double ended queue)Adt using B) // DEQUEUE USING DOUBLY LINKED LIST// import java.util.*; class Dequell { Node front; Node rear; class Node { int i; Node next; Node prev; Node(int i) { this.i = i; } } Dequell() { this.front = null; this.rear = null; } boolean isEmpty() { return front == null; } void insertfront(int i) { Node newNode = new Node(i); if(isEmpty()) { rear = newNode; } else { front.prev = newNode; }
  • 47. DATA STRUCTURES USING JAVA LAB 47 203C1A0405 newNode.next = front; front = newNode; } void insertrear(int i) { Node newNode = new Node(i); if(isEmpty()) { front = newNode; } else { rear.next = newNode; newNode.prev = rear; } rear = newNode; } void removefront() { if(isEmpty()) System.out.print("UnderFlown"); else { Node temp = front; if(front.next == null) { rear = null; } else { front.next.prev = null; } front = front.next; System.out.println("Node "+ temp.i + " deleted"); } } void removerear() { if(isEmpty()) System.out.print("UnderFlown"); else { Node temp = rear;
  • 48. DATA STRUCTURES USING JAVA LAB 48 203C1A0405 if(rear.next == null) { front = null; } else { rear.prev.next = null; } rear = rear.prev; System.out.println("Node "+ temp.i + " deleted"); } } void getfront() { if(isEmpty()) System.out.print("UnderFlown"); else System.out.println("The front element is: "+front.i); } void getrear() { if(isEmpty()) System.out.print("UnderFlown"); else System.out.println("The front element is: "+rear.i); } void displayforward() { Node current = front; while(current != null) { System.out.print(current.i + " "); current = current.next; } } void displaybackward() { Node current = rear; while(current != null) { System.out.print(current.i + " "); current = current.prev;
  • 49. DATA STRUCTURES USING JAVA LAB 49 203C1A0405 } } } class Dql { public static void main(String[] args) { Dequell dq = new Dequell(); System.out.print("********** DeQueue using Doubly Linked List **********"); boolean flag=true; Scanner in = new Scanner(System.in); int ch, num,x; while(flag) { System.out.print("n 1.INSERT FRONT n 2.INSERT REARn 3.REMOVE FRONTn 4.REMOVE REARn 5.GET FRONTn 6.GET REARn 7.DISPLAY FORWARDn 8.DISPLAY BACKWARD n 9.EXITnEnter your choice : "); ch = in.nextInt(); switch(ch) { case 1: System.out.print(" Enter a number you want to insert in front of Dequeue : "); num = in.nextInt(); dq.insertfront(num); break; case 2: System.out.print(" Enter a number you want to insert in rear of Dequeue : "); num = in.nextInt(); dq.insertrear(num); break; case 3: dq.removefront(); break; case 4: dq.removerear(); break; case 5: dq.getfront(); break; case 6:
  • 50. DATA STRUCTURES USING JAVA LAB 50 203C1A0405 dq.getrear(); break; case 7: dq.displayforward(); break; case 8: dq.displaybackward(); break; case 9: flag=false; } } } }
  • 51. DATA STRUCTURES USING JAVA LAB 51 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac Dequell.java C:UsersDMSSVHDesktop203C1A0405>java Dequell ********** DeQueue using Doubly Linked List ********** 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 1 Enter a number you want to insert in front of Dequeue : 10 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 1 Enter a number you want to insert in front of Dequeue : 20 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT
  • 52. DATA STRUCTURES USING JAVA LAB 52 203C1A0405 Enter your choice : 1 Enter a number you want to insert in front of Dequeue : 30 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 7 30 20 10 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 2 Enter a number you want to insert in rear of Dequeue : 11 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 2 Enter a number you want to insert in rear of Dequeue : 22 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD
  • 53. DATA STRUCTURES USING JAVA LAB 53 203C1A0405 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 2 Enter a number you want to insert in rear of Dequeue : 33 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 7 30 20 10 11 22 33 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 5 The front element is: 30 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 6 The front element is: 33 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT
  • 54. DATA STRUCTURES USING JAVA LAB 54 203C1A0405 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice : 8 33 22 11 10 20 30 1.INSERT FRONT 2.INSERT REAR 3.REMOVE FRONT 4.REMOVE REAR 5.GET FRONT 6.GET REAR 7.DISPLAY FORWARD 8.DISPLAY BACKWARD 9. EXIT Enter your choice :
  • 55. DATA STRUCTURES USING JAVA LAB 55 203C1A0405 7.Write a java program to implement priority queue ADT? import java.util.Scanner; class Task { String job; int priority; public Task(String job, int priority) { this.job = job; this.priority = priority; } public String toString() { return "Job Name : "+ job +"nPriority : "+ priority; } } class PriQueue { Task[] heap; int heapSize, capacity; public PriQueue(int capacity) { this.capacity = capacity + 1; heap = new Task[this.capacity]; heapSize = 0; } public void clear() { heap = new Task[capacity]; heapSize = 0; } public boolean isEmpty() { return heapSize == 0; } public boolean isFull() {
  • 56. DATA STRUCTURES USING JAVA LAB 56 203C1A0405 return heapSize == capacity - 1; } public int size() { return heapSize; } public void insert(String job, int priority) { Task newJob = new Task(job, priority); heap[++heapSize] = newJob; int pos = heapSize; while (pos != 1 && newJob.priority > heap[pos/2].priority) { heap[pos] = heap[pos/2]; pos /=2; } heap[pos] = newJob; } public Task remove() { int parent, child; Task item, temp; item = heap[1]; temp = heap[heapSize--]; parent = 1; child = 2; while (child <= heapSize) { if (child < heapSize && heap[child].priority < heap[child + 1].priority) child++; if (temp.priority >= heap[child].priority) break; heap[parent] = heap[child]; parent = child; child *= 2; } heap[parent] = temp; return item; } public void display() { int i;
  • 57. DATA STRUCTURES USING JAVA LAB 57 203C1A0405 System.out.print("JobName Priorityn"); for(i=1;i<=heapSize;i++) System.out.println( heap[i].job +" "+ heap[i].priority); } } public class PriQueueTest { public static void main(String[] args) { System.out.println("********** Priority Queue **********"); boolean flag=true; Scanner in = new Scanner(System.in); int ch, num,x; System.out.print("Enter size of priority queue: "); PriQueue pq = new PriQueue(in.nextInt() ); while(flag) { System.out.print("n1.Insertn2.Removen3.Check Emptyn4.Check Fulln5.Clearn6.Sizen7.Displayn8.Exit nEnter your choice :"); ch = in.nextInt(); switch(ch) { case 1:if(pq.isFull()) System.out.println("Priority Queue Full"); else { System.out.println("Enter job name and priority"); pq.insert(in.next(), in.nextInt() ); } break; case 2 :if(pq.isEmpty()) System.out.println("Priority Queue Empty"); else System.out.println("nJob removed nn"+ pq.remove()); break; case 3 : System.out.println("nEmpty Status : "+ pq.isEmpty() ); break; case 4 : System.out.println("nFull Status : "+ pq.isFull() ); break; case 5 :
  • 58. DATA STRUCTURES USING JAVA LAB 58 203C1A0405 System.out.println("nPriority Queue Cleared"); pq.clear(); break; case 6 : System.out.println("nSize = "+ pq.size() ); break; case 7: pq.display(); break; case 8: flag=false; } } } }
  • 59. DATA STRUCTURES USING JAVA LAB 59 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac PriQueueTest.java C:UsersDMSSVHDesktop203C1A0405>java PriQueueTest ********** Priority Queue ********** Enter size of priority queue: 3 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :1 Enter job name and priority j1 23 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :1 Enter job name and priority j2 56 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :1 Enter job name and priority
  • 60. DATA STRUCTURES USING JAVA LAB 60 203C1A0405 j3 78 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :7 JobName Priority j3 78 j1 23 j2 56 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :3 Empty Status : false 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :4 Full Status : true 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit
  • 61. DATA STRUCTURES USING JAVA LAB 61 203C1A0405 Enter your choice :6 Size = 3 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :2 Job removed Job Name : j3 Priority : 78 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :2 Job removed Job Name : j2 Priority : 56 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :2 Job removed Job Name : j1 Priority : 23 1.Insert 2.Remove 3.Check Empty 4.Check Full
  • 62. DATA STRUCTURES USING JAVA LAB 62 203C1A0405 5.Clear 6.Size 7.Display 8.Exit Enter your choice :2 Priority Queue Empty 1.Insert 2.Remove 3.Check Empty 4.Check Full 5.Clear 6.Size 7.Display 8.Exit Enter your choice :
  • 63. DATA STRUCTURES USING JAVA LAB 63 203C1A0405 8. Write Java programs that use recursive and non-recursive functions to traverse the given binary tree in (a) Preorder (b) In order and (c) Post order. import java.util.Stack; class Node { Object data; Node left; Node right; Node( Object d ) // constructor { data = d; } } class BinaryTree { Object tree[]; int maxSize; Stack<Node>stk = new 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); }
  • 64. DATA STRUCTURES USING JAVA LAB 64 203C1A0405 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();
  • 65. DATA STRUCTURES USING JAVA LAB 65 203C1A0405 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 ) {
  • 66. DATA STRUCTURES USING JAVA LAB 66 203C1A0405 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 BinaryTreeTest { public static void main(String args[]) { Object arr[] ={'A','B','C','D','E','F','G', 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); } }
  • 67. DATA STRUCTURES USING JAVA LAB 67 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac BinaryTreeTest.java C:UsersDMSSVHDesktop203C1A0405>java BinaryTreeTest Recursive Binary Tree Traversals: inorder:D B E A F C G preorder:A B D E C F G postorder:D E B F G C A Non-recursive Binary Tree Traversals: inorder:D B E A F C G preorder:A B D E C F G postorder:D E B F G C A
  • 68. DATA STRUCTURES USING JAVA LAB 68 203C1A0405 9. Write a Java program that displays node values in a level order traversal (Traverse the tree one level at a time, starting at the root node) for a binary tree. import java.util.Queue; import java.util.LinkedList; import java.util.*; public class Tree { static Node root; static class Node { int data; Node left; Node right; Node( int d ) // constructor { this.data = d; } } public Node BuildTree( int arr[], int i ) { Node root=null; if(i&lt;arr.length) { root=new Node(arr[i]); root.left=BuildTree(arr,2*i+1); root.right = BuildTree(arr,2*i+2); } return root; } public void printLevelOrder(Node root) { Queue&lt;Node&gt; queue = new LinkedList&lt;Node&gt;(); queue.add(root); while (!queue.isEmpty()) { Node tempNode = queue.poll(); System.out.print(tempNode.data + &quot; &quot;); if (tempNode.left != null) {
  • 69. DATA STRUCTURES USING JAVA LAB 69 203C1A0405 queue.add(tempNode.left); } if (tempNode.right != null) { queue.add(tempNode.right); } } } public void inorder(Node p) { if( p != null ) { inorder(p.left); System.out.print(p.data + &quot; &quot;); inorder(p.right); } } public static void main(String args[]) { Tree t=new Tree(); int[] arr=new int[6]; Scanner in = new Scanner(System.in); int i; for(i=0;i&lt;=5;i++) arr[i]=in.nextInt(); t.root=t.BuildTree(arr,0); System.out.print(&quot;n Level Order Traversal: &quot;); t.printLevelOrder(root); System.out.print(&quot;n InOrder Traversal: &quot;); t.inorder(root); } }
  • 70. DATA STRUCTURES USING JAVA LAB 70 203C1A0405 OUTPUT: C:UsersDMSSVHDesktop203C1A0405>javac Tree.java C:UsersDMSSVHDesktop203C1A0405>java Tree 1 2 3 4 5 6 Level Order Traversal: 1 2 3 4 5 6 InOrder Traversal: 4 2 5 1 6 3
  • 71. DATA STRUCTURES USING JAVA LAB 71 203C1A0405 10. Write a Java program that uses recursive functions. (a) To create a binary search tree. (b) To count the number of leaf nodes. (c) To copy the above binary search tree. import java.util.*; class Node { int data; Node left, right; Node(int key) { data = key; left = right = null; } } class BST { public static void inorder(Node root) { if (root == null) { return; } inorder(root.left); System.out.print(root.data + &quot; &quot;); inorder(root.right); } public static Node insert(Node root, int key) { if (root == null) { return new Node(key); } if (key &lt; root.data) {
  • 72. DATA STRUCTURES USING JAVA LAB 72 203C1A0405 root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } int getLeafCount(Node node) { if (node == null) return 0; if (node.left == null &amp;&amp; node.right == null) return 1; else return getLeafCount(node.left) + getLeafCount(node.right); } Node cloneBST(Node root) { if (root == null) { return null; } Node root_copy = new Node(root.data); root_copy.left = cloneBST(root.left); root_copy.right = cloneBST(root.right); return root_copy; } } class BSTMain { public static void main(String[] args) { int key; boolean flag=true; Scanner in = new Scanner(System.in); int ch, n; Node root=null,root_copy=null;; BST b=new BST(); while(flag) { System.out.print(&quot;n1.Create BSTn2.Count Leavesn3.Copy Treen4.Inorder
  • 73. DATA STRUCTURES USING JAVA LAB 73 203C1A0405 traversaln5.ExitnEnter your Choice: &quot;); ch = in.nextInt(); switch(ch) { case 1: System.out.print(&quot;nEnter the number of keys:&quot;); n=in.nextInt(); System.out.println(&quot;nEnter &quot;+n+&quot; Keys:&quot;); for(int i=1;i&lt;=n;i++) { key=in.nextInt(); root=b.insert(root,key); } break; case 2: System.out.print(&quot;Number of leaf nodes: &quot;+b.getLeafCount(root)); break; case 3: root_copy=b.cloneBST(root); System.out.println(&quot;BST is copied,New Tree Inorder traversal:n&quot;); b.inorder(root_copy); break; case 4: b.inorder(root); break; case 5: flag=false; } } } }
  • 74. DATA STRUCTURES USING JAVA LAB 74 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac BSTMain.java C:UsersDMSSVHDesktop203C1A0405>java BSTMain 1.Create BST 2.Count Leaves 3.Copy Tree 4.Inorder traversal 5.Exit Enter your Choice: 1 Enter the number of keys:6 Enter 6 Keys: 50 70 80 15 30 68 1.Create BST 2.Count Leaves 3.Copy Tree 4.Inorder traversal 5.Exit Enter your Choice: 2 Number of leaf nodes: 3 1.Create BST 2.Count Leaves 3.Copy Tree 4.Inorder traversal 5.Exit Enter your Choice: 4 15 30 50 68 70 80 1.Create BST 2.Count Leaves 3.Copy Tree 4.Inorder traversal 5.Exit
  • 75. DATA STRUCTURES USING JAVA LAB 75 203C1A0405 Enter your Choice: 3 BST is copied,New Tree Inorder traversal: 15 30 50 68 70 80 1.Create BST 2.Count Leaves 3.Copy Tree 4.Inorder traversal 5.Exit Enter your Choice: 5
  • 76. DATA STRUCTURES USING JAVA LAB 76 203C1A0405 11. Write Java programs for the implementation of bfs and dfs for a given graph? import java.util.*; class GTraversal { int N; int [][]adj; int[] visited; LinkedList<Integer> q=new LinkedList<Integer>(); GTraversal(int n) { N=n; adj=new int[N][N]; visited=new int[N]; for(int i=0;i<N;i++) visited[i]=0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) adj[i][j]=0; } void addEdge(int u,int v) { adj[u][v]=1; adj[v][u]=1; } public void printMatrix() { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { System.out.print(+adj[i][j]+" ");
  • 77. DATA STRUCTURES USING JAVA LAB 77 203C1A0405 } System.out.print("n"); } } void BFS(int s) { q.add(s); visited[s]=1; while(!q.isEmpty()) { int x=q.poll(); System.out.print(x+" "); for(int i=0;i<N;i++) { if(adj[x][i]==1 && (visited[i]==0)) { q.add(i); visited[i]=1; } } } } void DFS(int s) { int j; System.out.print(s+" "); visited[s]=1; for(j=0;j<N;j++) if(visited[j]==0&&adj[s][j]==1) DFS(j); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int num,e,u,v; System.out.println("Enter the number of vertices:"); num=in.nextInt(); GTraversal g=new GTraversal(num); GTraversal g1=new GTraversal(num); System.out.println("Enter the Number of Edges:");
  • 78. DATA STRUCTURES USING JAVA LAB 78 203C1A0405 e=in.nextInt(); System.out.println("Enter the Edges:"); for(int i=1;i<=e;i++) { u=in.nextInt(); v=in.nextInt(); g.addEdge(u,v); g1.addEdge(u,v); } g.printMatrix(); System.out.println("BFS"); g.BFS(0); System.out.println("nDFS"); g1.DFS(0); } }
  • 79. DATA STRUCTURES USING JAVA LAB 79 203C1A0405 Output: C:UsersstaffDesktopJAVA>java GTraversal Enter the number of vertices: 7 Enter the Number of Edges: 11 Enter the Edges: 0 1 0 3 1 3 1 2 2 3 2 4 2 5 3 4 4 6 6 1 1 5 0 1 0 1 0 0 0 1 0 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 0 0 0 1 1 0 0 1 0 1 1 0 0 0 0 0 1 0 0 1 0 0 BFS 0 1 3 2 5 6 4 DFS 0 1 2 3 4 6 5
  • 80. DATA STRUCTURES USING JAVA LAB 80 203C1A0405 12 . write java program for implementing the following sorting methods: a) Bubble sort import java.util.*; class BubbleSort { void BubbleSort(int arr[],int n) { for(int i=0;i<n-1;i++) for(int j=0;j<n-i-1;j++) if(arr[j]>arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } void printArray(int arr[]) { int n=arr.length; for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } public static void main(String[]args) { BubbleSort ob = new BubbleSort(); int n; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements:"); n=sc.nextInt(); int[]arr=new int[n]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); }
  • 81. DATA STRUCTURES USING JAVA LAB 81 203C1A0405 ob.BubbleSort(arr,n); System.out.println("Sorted array-BubbleSort"); ob.printArray(arr); } } Output : C:UsersDMSSVHDesktop203C1A0405>javac BubbleSort.java C:UsersDMSSVHDesktop203C1A0405>java BubbleSort Enter the number of elements:5 Enter the elements of the array: 10 20 30 40 50 Sorted array-BubbleSort 10 20 30 40 50
  • 82. DATA STRUCTURES USING JAVA LAB 82 203C1A0405 b) Selection Sort import java.util.*; class SelectionSort { void SelectionSort(int arr[],int n) { int k,pos,temp; for(k=0;k<n;k++) { pos = smallest(arr,k,n); temp = arr[k]; arr[k] = arr[pos]; arr[pos] = temp; } } int smallest(int arr[],int k,int n) { int pos = k,small=arr[k],i; for(i=k+1;i<n;i++) { if(arr[i]<small) { small=arr[i]; pos=i; } } return pos; } void printArray(int arr[]) { int n=arr.length; for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } public static void main(String[]args)
  • 83. DATA STRUCTURES USING JAVA LAB 83 203C1A0405 { SelectionSort s = new SelectionSort(); int n; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements:"); n=sc.nextInt(); int[]arr=new int[n]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } s.SelectionSort(arr,n); System.out.println("Sorted array-SelectionSort"); s.printArray(arr); } }
  • 84. DATA STRUCTURES USING JAVA LAB 84 203C1A0405 Output : C:UsersDMSSVHDesktop203C1A0405>javac SelectionSort.java C:UsersDMSSVHDesktop203C1A0405>java SelectionSort Enter the number of elements:5 Enter the elements of the array: 21 22 23 24 25 Sorted array-SelectionSort 21 22 23 24 25
  • 85. DATA STRUCTURES USING JAVA LAB 85 203C1A0405 C) Insert Sort import java.util.*; public class InsertSort { void InsertSort(int arr[]) { int n = arr.length; for(int i=1;i<n;i++) { int key = arr[i]; int j=i-1; while(j>=0&&arr[j]>key) { arr[j+1]=arr[j]; j = j-1; } arr[j+1]=key; } } void printArray(int arr[]) { int n=arr.length; for(int i=0;i<n;i++) System.out.print(arr[i]+" "); System.out.println(); } public static void main(String[]args) { SelectionSort s = new SelectionSort(); int n; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements:"); n=sc.nextInt(); int[]arr1=new int[n]; System.out.println("Enter the elements of the array:"); for(int i=0;i<n;i++) {
  • 86. DATA STRUCTURES USING JAVA LAB 86 203C1A0405 arr1[i]=sc.nextInt(); } InsertSort ob = new InsertSort(); ob.InsertSort(arr1); ob.printArray(arr1) }} Output : C:UsersDMSSVHDesktop203C1A0405>javac InsertSort.java C:UsersDMSSVHDesktop203C1A0405>java InsertSort Enter the number of elements:5 Enter the elements of the array: 71 72 73 74 75 71 72 73 74 75
  • 87. DATA STRUCTURES USING JAVA LAB 87 203C1A0405 13. Write a Java program for implementing KMP pattern matching algorithm. import java.util.*; class KMP { void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); int lps[] = new int[M]; int j = 0; computeLPSArray(pat, M, lps); int i = 0; while ((N - i) >= (M - j)) { 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]; } else if (i < N && pat.charAt(j) != txt.charAt(i)) { if (j != 0) j = lps[j - 1]; else
  • 88. DATA STRUCTURES USING JAVA LAB 88 203C1A0405 i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } } public static void main(String args[]) { String txt,pat; Scanner sc= new Scanner(System.in); System.out.print("Enter a string: "); txt=sc.nextLine(); System.out.print("enter the pattern string: "); pat=sc.nextLine();
  • 89. DATA STRUCTURES USING JAVA LAB 89 203C1A0405 new KMP().kmpSearch(pat,str); } } Output : C:UsersDMSSVHDesktop203C1A0405>javac KMP.java C:UsersDMSSVHDesktop203C1A0405>java KMP Enter a string: sushmasushmasushma enter the pattern string: ma Found pattern at index 4 Found pattern at index 10 Found pattern at index 16 C:UsersDMSSVHDesktop203C1A0405>javac KMP.java C:UsersDMSSVHDesktop203C1A0405>java KMP Enter a string: heyhiheyheyhi enter the pattern string: he Found pattern at index 0 Found pattern at index 5 Found pattern at index 8