DS Using Java on Novb 10 (1)
DS Using Java on Novb 10 (1)
2. Write Java programs to implement the List ADT using arrays and linked lists.
4. Write a java program that reads an infix expression, converts the expression to
postfix form
5. Write Java programs to implement the following using a singly linked list.
6. Write Java programs to implement the deque (double ended queue) ADT using
(a) Array
(a) Preorder
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.
11. Write Java programs for the implementation of bfs and dfs for a given graph.
12. Write Java programs for implementing the following sorting methods:
13. Write a Java program for implementing KMP pattern matching algorithm.
1. Write Java programs that use both recursive and non-recursive functions for
implementing
import java.io.*;
class LinearSearch
int count=0;
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
int key=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
if(arr[i]==key)
count++;
if(count==n)
OUTPUT:
import java.io.*;
class RecursiveLinearSearch
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
key=Integer.parseInt(br.readLine());
if( linearSearch(arr.length-1) )
else
if(key == arr[n])
return true;
else
return linearSearch(n-1);
OUTPUT:
import java.io.*;
class RecursiveBinarySearch
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
}
key=Integer.parseInt(br.readLine());
else
int c = ((Comparable)key).compareTo(arr[mid]);
OUTPUT:
2. Write Java programs to implement the List ADT using arrays and linked lists.
class Node {
Object data;
int next;
data = ob;
next = i;
MAXSIZE = s;
int p;
count++;
return;
int p = getNode();
if( p != -1 ) {
list[p].data = item;
head = p;
count++;
System.out.println("***List is FULL");
return;
if( q != -1 ) {
list[q].data = item;
list[q].next = list[p].next;
list[p].next = q;
count++;
return -1;
public int find(Object ob) // find the index (position) of the Object ob
int p = head;
while( p != -1) {
return -1;
if( isEmpty() ) {
return null;
}
Object tmp = list[head].data;
else
head = list[head].next;
return tmp;
int p = find(x);
if( p == -1 || list[p].next == -1 ) {
System.out.println("No deletion");
return null;
int q = list[p].next;
list[p].next = list[q].next;
count--;
return tmp;
int p = head;
System.out.print("¥nList: [ " );
while( p != -1) {
System.out.println("]¥n");//
return count;
class ArrayListDemo {
linkedList.initializeList();
System.out.print("InsertFirst 55:");
linkedList.insertFirst(55);
linkedList.display();
System.out.print("Insert 66 after 33:");
linkedList.display();
linkedList.display();
System.out.print("InsertFirst 77:");
linkedList.insertFirst(77);
linkedList.display();
linkedList.display();
Output:
List: [ 11 22 33 44 ]
InsertFirst 55:
List: [ 55 11 22 33 44 ]
List: [ 55 11 22 33 66 44 ]
Deleted node: 55
List: [ 11 22 33 66 44 ]
InsertFirst 77:
List: [ 77 11 22 33 66 44 ]
Deleted node: 33
List: [ 77 11 22 66 44 ]
size(): 5
class Node {
count = n;
}
count++;
if( p == null )
else{
count++;
p = head;
{
if( p.data == key ) return p;
if( isEmpty() ){
return null;
head = tmp.next;
count--;
return tmp.data;
if( p == null ){
return null;
System.out.println("No deletion");
return null;
else{
count--;
{
return (head == null);
return count;
class LinkedListDemo {
list.displayList();
list.displayList();
list.displayList();
list.displayList();
Output:
deleteFirst(): 55
deleteAfter(22): 33
size(): 4
import java.io.*;
class stackclass
int top,ele,stack[],size;
stackclass(int n)
{
stack=new int[n];
size=n;
top= -1;
void push(int x)
ele=x;
stack[++top]=ele;
int pop()
if(!isempty())
return stack[top--];
else
System.out.println("stack is empty");
return -1;
boolean isempty()
{
if(top==-1)
return true;
else
return false;
boolean isfull()
if(size>(top+1))
return false;
else
return true;
int peek()
if(!isempty())
return stack[top];
else
System.out.println("stack is empty");
return -1;
}
void size()
void display()
if(!isempty())
for(int i=top;i>=0;i--)
System.out.print(stack[i]+" ");
else
System.out.println("stack is empty");
class stacktest
int size=Integer.parseInt(br.readLine());
do
System.out.println();
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.peek");
System.out.println("4.size");
System.out.println("5.display");
System.out.println("6.is empty");
System.out.println("7.is full");
System.out.println("8.exit");
ch=Integer.parseInt(br.readLine());
switch(ch)
case 1:if(!s.isfull())
ele=Integer.parseInt(br.readLine());
s.push(ele);
else
{
System.out.print("stack is overflow");
break;
if(del!=-1)
System.out.println(del+" is deleted");
break;
if(p!=-1)
break;
case 4:s.size();
break;
case 5:s.display();
break;
System.out.println(b);
break;
System.out.println(b1);
break;
case 8 :System.exit(1);
}
}while(ch!=0);
OUTPUT:
3(b)Queue ADT using array
import java.util.*;
class queue
int front,rear;
int que[];
int max,count=0;
queue(int n)
max=n;
que=new int[max];
front=rear=-1;
boolean isfull()
if(rear==(max-1))
return true;
else
return false;
boolean isempty()
if(front==-1)
return true;
else
return false;
void insert(int n)
if(isfull())
System.out.println("list is full");
else
rear++;
que[rear]=n;
if(front==-1)
front=0;
count++;
int delete()
int x;
if(isempty())
return -1;
else
{
x=que[front];
que[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
count--;
return x;
void display()
if(isempty())
System.out.println("queue is empty");
else
for(int i=front;i<=rear;i++)
System.out.println(que[i]);
int size()
return count;
}
public static void main(String args[])
int ch;
System.out.println("enter limit");
int n=s.nextInt();
do
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
ch=s.nextInt();
switch(ch)
int n1=s.nextInt();
q.insert(n1);
if(c1>0)
System.out.println("can't delete");
break;
case 3:q.display();
break;
break;
while(ch!=0);
OUTPUT:
4. Write a java program that reads an infix expression, converts the expression to
postfix form
import java.io.*;
class InfixToPostfix
ch = infix.charAt(i);
if( isOperator(item) )
stk.push(item);
stk.push(ch);
else
stk.push(ch);
}
}
else
stk.push(item);
stk.push(ch);
} // end of if(isOperator(ch))
if( ch == ')' )
item = stk.pop();
item = stk.pop();
} // end of for-loop
return postfix;
}
public boolean isOperator(char c)
return rank;
//InfixToPostfixDemo.java
class InfixToPostfixDemo
System.out.println("Enter Expression:");
System.out.println("postfix:"+obj.toPostfix(infix) );
}
OUTPUT:
6. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT (b) Queue ADT
//6 (a) Stack
import java.io.*;
class Stack1
{
Stack1 top,next,prev;
int data;
Stack1()
{
data=0;
next=prev=null;
}
Stack1(int d)
{
data=d;
next=prev=null;
}
void push(int n)
{
Stack1 nn;
nn=new Stack1(n);
if(top==null)
top=nn;
else
{
nn.next=top;
top.prev=nn;
top=nn;
}
}
int pop()
{
int k=top.data;
if(top.next==null)
{
top=null;
return k;
}
else
{
top=top.next;
top.prev=null;
return k;
}
}
boolean isEmpty()
{
if(top==null)
return true;
else
return false;
}
void display()
{
Stack1 ptr;
for(ptr=top;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
public static void main(String args[ ])throws Exception
{
int x;
int ch;
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
Stack1 a=new Stack1();
do{
System.out.println("enter 1 for pushing");
System.out.println("enter 2 for poping");
System.out.println("enter 3 for isEmpty");
System.out.println("enter 4 for display");
System.out.println("Enter 0 for exit");
System.out.println("enter ur choice ");
ch=Integer.parseInt(b.readLine());
switch(ch)
{
case 1:System.out.println("enter element to insert");
int e=Integer.parseInt(b.readLine());
a.push(e);
break;
case 2:if(!a.isEmpty())
{
int p=a.pop();
System.out.println("deleted element is "+p);
}
else
{
System.out.println("stack is empty");
}
break;
case 3:System.out.println(a.isEmpty());
break;
case 4:if(!a.isEmpty())
{
a.display();
}
else
{
System.out.println("list is empty");
}
}
}while(ch!=0);
}
}
OUTPUT:
6 (b). Queue
import java.io.*;
class Qlnk
{
Qlnk front,rear,next;
int data;
Qlnk()
{
data=0;
next=null;
}
Qlnk(int d)
{
data=d;
next=null;
}
Qlnk getFront()
{
return front;
}
Qlnk getRear()
{
return rear;
}
void insertelm(int item)
{
Qlnk nn;
nn=new Qlnk(item);
if(isEmpty())
{
front=rear=nn;
}
else
{
rear.next=nn;
rear=nn;
}
}
int delelm()
{
if(isEmpty())
{
System.out.println("deletion failed");
return -1;
}
else
{
int k=front.data;
if(front!=rear)
front=front.next;
else
rear=front=null;
return k;
}
}
boolean isEmpty()
{
if(rear==null)
return true;
else
return false;
}
int size(){
Qlnk ptr;
int cnt=0;
for(ptr=front;ptr!=null;ptr=ptr.next)
cnt++;
return cnt;
}
void display()
{
Qlnk ptr;
if(!isEmpty())
{
for(ptr=front;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
}
else
System.out.println("q is empty");
}
public static void main(String arr[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Qlnk m=new Qlnk();
int ch;
do
{
System.out.println("enter 1 for insert");
System.out.println("enter 2 for deletion");
System.out.println("enter 3 for getFront");
System.out.println("enter 4 for getRear");
System.out.println("enter 5 for size");
System.out.println("enter 6 for display");
System.out.println("enter 0 for exit");
System.out.println("enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("enter ele to insert");
int item=Integer.parseInt(br.readLine());
m.insertelm(item);break;
case 2:int k=m.delelm();
System.out.println("deleted ele is "+k);break;
case 3:System.out.println("front index is"+(m.getFront()).data);break;
case 4:System.out.println("rear index is"+(m.getRear()).data);break;
case 5:System.out.println("size is"+m.size());break;
case 6:m.display();break;
}
}while(ch!=0);
}
}
OUTPUT:
8. Write Java programs to implement the deque (double ended queue) ADT
using
(a) Array
(b) Doubly linked list.
(a): An ArrayDeque Class
public class ArrayDeque {
private int maxSize;
private Object[] que;
private int first;
private int last;
private int count; // current number of items in deque
public ArrayDeque(int s) { // constructor
maxSize = s;
que = new Object[maxSize];
first = last = -1;
count = 0;
}
public void addLast(Object item) {
if(count == maxSize) {
System.out.println("Deque is full"); return;
}
last = (last+1) % maxSize;
que[last] = item;
if(first == -1 && last == 0) first = 0;
count++;
}
public Object removeLast() {
if(count == 0) {
System.out.println("Deque is empty"); return(' ');
}
Object item = que[last];
que[last] = „ ‟;
if(last > 0)
last = (last-1) % maxSize;
count--;
if(count == 0)
first = last = -1;
return(item);
}
public void addFirst(Object item){
if(count == maxSize){
System.out.println("Deque is full"); return;
}
if(first > 0)
first = (first-1) % maxSize;
else if(first == 0)
first = maxSize-1;
que[first] = item;
count++;
}
public Object removeFirst() {
if(count == 0) {
System.out.println("Deque is empty");
return(' ');
}
Object item = que[first];
que[first] = „ ‟;
if(first == maxSize-1)
first = 0;
else
first = (first+1) % maxSize;
count--;
if(count == 0)
first = last = -1;
return(item);
}
void display() {
System.out.println("----------------------------");
System.out.print("first:"+first + ", last:"+ last);
System.out.println(", count: " + count);
System.out.println(" 0 1 2 3 4 5");
System.out.print("Deque: ");
for( int i=0; i<maxSize; i++ )
System.out.print(que[i]+ " ");
System.out.println("¥n----------------------------");
}
public boolean isEmpty(){ // true if queue is empty
return (count == 0);
}
public boolean isFull(){ // true if queue is full
return (count == maxSize);
}
}
class ArrayDequeDemo {
public static void main(String[] args) {
ArrayDeque q = new ArrayDeque(6); // queue holds a max of 6 items
q.insertLast('A'); /* (a) */
q.insertLast('B');
q.insertLast('C');
q.insertLast('D');
System.out.println("deleteFirst():"+q.deleteFirst());
q.display();
q.insertLast('E'); /* (b) */
q.display(); /* (c) */
System.out.println("deleteLast():"+q.deleteLast());
System.out.println("deleteLast():"+q.deleteLast());
q.display();
q.insertFirst('P'); q.insertFirst('Q'); /* (d) */
q.insertFirst('R'); q.display();
q.deleteFirst(); q.display(); /* (e) */
q.insertFirst('X'); q.display(); /* (f) */
q.insertLast('Y'); q.display(); /* (g) */
q.insertLast('Z'); q.display(); /* (h) */
}
}
Output:
deleteFirst(): A
----------------------------
first:1, last:3, count: 3
012345
Deque: B C D
----------------------------
first:1, last:4, count: 4
012345
Deque: B C D E
----------------------------
deleteLast(): E
deleteLast(): D
----------------------------
first:1, last:2, count: 2
012345
Deque: B C
----------------------------
first:4, last:2, count: 5
012345
Deque: P B C R Q
----------------------------
first:5, last:2, count: 4
012345
Deque: P B C Q
----------------------------
first:4, last:2, count: 5
012345
Deque: P B C X Q
----------------------------
first:4, last:3, count: 6
012345
Deque: P B C Y X Q
----------------------------
Deque is full
----------------------------
first:4, last:3, count: 6
012345
Deque: P B C Y X Q
----------------------------
(b): A LinkedDeque class
public class LinkedDeque {
public class DequeNode {
DequeNode prev;
Object data;
DequeNode next;
DequeNode( Object item ) // constructor
{
data = item;
} // prev & next automatically refer to null
}
private DequeNode first, last;
private int count;
public void addFirst(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else {
DequeNode tmp = new DequeNode(item);
tmp.next = first;
first.prev = tmp;
first = tmp;
}
count++;
}
public void addLast(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else{
DequeNode tmp = new DequeNode(item);
tmp.prev = last;
last.next = tmp;
last = tmp;
}
count++;
}
public Object removeFirst(){
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = first.data;
first = first.next;
first.prev = null;
count--;
return item;
}
}
public Object removeLast() {
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = last.data;
last = last.prev;
last.next = null;
count--;
return item;
}
}
public Object getFirst(){
if( !isEmpty() )
return( first.data );
else
return null;
}
public Object getLast(){
if( !isEmpty() )
return( last.data );
else
return null;
}
public boolean isEmpty(){
return (count == 0);
}
public int size(){
return(count);
}
public void display(){
DequeNode p = first;
System.out.print("Deque: [ ");
while( p != null ){
System.out.print( p.data + " " );
p = p.next;
}
System.out.println("]");
}
}
public class LinkedDequeDemo {
public static void main( String args[]){
LinkedDeque dq = new LinkedDeque();
System.out.println("removeFirst():" + dq.removeFirst());
dq.addFirst('A');
dq.addFirst('B');
dq.addFirst('C');
dq.display();
dq.addLast('D');
dq.addLast('E');
System.out.println("getFirst():" + dq.getFirst());
System.out.println("getLast():" + dq.getLast());
dq.display();
System.out.println("removeFirst():"+dq.removeFirst());
System.out.println("removeLast():"+ dq.removeLast());
dq.display();
System.out.println("size():" + dq.size());
}
}
Output:
Deque is empty
removeFirst(): null
Deque: [ C B A ]
getFirst(): C
getLast(): E
Deque: [ C B A D E ]
removeFirst(): C
removeLast(): E
Deque: [ B A D ]
size(): 3
9. Write a Java program to implement a priority queue ADT.
public class Node {
String data; // data item
int prn; // priority number (minimum has highest priority)
Node next; // "next" refers to the next node
Node( String str, int p ) { // constructor
data = str;
prn = p;
} // "next" is automatically set to null
}
class LinkedPriorityQueue {
Node head; // “head” refers to first node
public void insert(String item, int pkey){ // insert item after pkey
Node newNode = new Node(item, pkey); // create new node
int k;
if( head == null )
k = 1;
else if( newNode.prn < head.prn )
k = 2;
else
k = 3;
switch( k ){
case 1: head = newNode; // Q is empty, add head node
head.next = null;
break;
case 2: Node oldHead = head; // add one item before head
head = newNode;
newNode.next = oldHead;
break;
case 3: Node p = head; // add item before a node
Node prev = p;
Node nodeBefore = null;
while( p != null ) {
if( newNode.prn < p.prn ){
nodeBefore = p; break;
}
else {
prev = p; // save previous node of current node
p = p.next; // move to next node
}
} // end of while
newNode.next = nodeBefore;
prev.next = newNode;
} // end of switch
} // end of insert() method
public Node delete(){
if( isEmpty() ){
System.out.println("Queue is empty");
return null;
}
else {
Node tmp = head;
head = head.next;
return tmp;
}
}
public void displayList() {
Node p = head; // assign address of head to p
System.out.print("¥nQueue: ");
while( p != null ) // start at beginning of list until end of list
{
System.out.print(p.data+"(" +p.prn+ ")" + " ");
p = p.next; // move to next node
}
System.out.println();
}
public boolean isEmpty() // true if list is empty
{
return (head == null);
}
public Node peek() // get first item
{
return head;
}
class LinkedPriorityQueueDemo {
public static void main(String[] args){
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Babu", 3);
pq.insert("Nitin", 2);
pq.insert("Laxmi", 2);
pq.insert("Kim", 1);
pq.insert("Jimmy", 3);
pq.displayList();
item = pq.delete();
if( item != null )
System.out.println("delete():" + item.data + "(" +item.prn+")");
pq.displayList();
pq.insert("Scot", 2);
pq.insert("Anu", 1);
pq.insert("Lehar", 4);
pq.displayList();
}
}
Output:
Queue: Kim(1) Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
delete(): Kim(1)
Queue: Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
Queue: Anu(1) Nitin(2) Laxmi(2) Scot(2) Babu(3) Jimmy(3) Lehar(4)
10.Write Java programs that use recursive and non-recursive functions to
traverse the given binary
tree in Preorder b) Inorder c) Postorder.
class Node
{
Object data;
Node left;
Node right;
Node( Object d ) // constructor
{
data = d;
}
}
class BinaryTree
{
Object tree[];
int maxSize;
java.util.Stack<Node> stk = new java.util.Stack<Node>();
BinaryTree( Object a[], int n ) // constructor
{
maxSize = n;
tree = new Object[maxSize];
for( int i=0; i<maxSize; i++ )
tree[i] = a[i];
}
public Node buildTree( int index )
{
Node p = null;
if( tree[index] != null )
{
p = new Node(tree[index]);
p.left = buildTree(2*index+1);
p.right = buildTree(2*index+2);
}
return p;
}
/* Recursive methods - Binary tree traversals */
public void inorder(Node p)
{
if( p != null )
{
inorder(p.left);
System.out.print(p.data + " ");
inorder(p.right);
}
}
public void preorder(Node p)
{
if( p != null )
{
System.out.print(p.data + " ");
preorder(p.left);
preorder(p.right);
}
}
public void postorder(Node p)
{
if( p != null )
{
postorder(p.left);
postorder(p.right);
System.out.print(p.data + " ");
}
}
/* Non-recursive methods - Binary tree traversals */
public void preorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
stk.push(p);
while( !stk.isEmpty() )
{
p = stk.pop();
if( p != null )
{
System.out.print(p.data + " ");
stk.push(p.right);
stk.push(p.left);
}
}
}
public void inorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
while( !stk.isEmpty() || p != null )
{
if( p != null )
{
stk.push(p); // push left-most path onto stack
p = p.left;
}
else
{ p = stk.pop(); // assign popped node to p
System.out.print(p.data + " "); // print node data
p = p.right; // move p to right subtree
}
}
}
public void postorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
Node tmp = p;
while( p != null )
{
while( p.left != null )
{
stk.push(p);
p = p.left;
}
while( p != null && (p.right == null || p.right == tmp ))
{
System.out.print(p.data + " "); // print node data
tmp = p;
if( stk.isEmpty() )
return;
p = stk.pop();
}
stk.push(p);
p = p.right;
}
}
} // end of BinaryTree class
class BinaryTreeDemo
{
public static void main(String args[])
{
Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H', null,'B',
null, null, null, null, null, null, null, null, null, null };
BinaryTree t = new BinaryTree( arr, arr.length );
Node root = t.buildTree(0); // buildTree() returns reference to root
System.out.print("¥n Recursive Binary Tree Traversals:");
System.out.print("¥n inorder: ");
t.inorder(root);
System.out.print("¥n preorder: ");
t.preorder(root);
System.out.print("¥n postorder: ");
t.postorder(root);
System.out.print("¥n Non-recursive Binary Tree Traversals:");
System.out.print("¥n inorder: ");
t.inorderIterative(root);
System.out.print("¥n preorder: ");
t.preorderIterative(root);
System.out.print("¥n postorder: ");
t.postorderIterative(root);
}
}
11.Write Java programs for the implementation of bfs and dfs for a given
graph.
//bfs
import java.io.*;
class quelist
{
public int front;
public int rear;
public int maxsize;
public int[] que;
gr.addedge(start,end);
}
System.out.print("The vertices in the graph traversed breadthwise:");
gr.brfs();
}
}
//dfs
import java.io.*;
import java.util.*;
class Stack
{
int stk[]=new int[10];
int top;
Stack()
{
top=-1;
}
void push (int item)
{
if (top==9)
System.out.println("Stack overflow");
else
stk[++top]=item;
}/*end push*/
boolean isempty()
{
if (top<0)
return true;
else
return false;
}/*end isempty*/
int pop()
{
if (isempty())
{
System.out.println("Stack underflow");
return 0;
}
else
return (stk[top--]);
}/*end pop*/
void stacktop()
{
if(isempty())
System.out.println("Stack underflow ");
else
System.out.println("Stack top is "+(stk[top]));
}/*end stacktop*/
void display()
{
System.out.println("Stack-->"); for(int i=0;i<=top;i++)
System.out.println(stk[i]);
}/*end display*/
}
class Graph
{
int MAXSIZE=51;
int adj[][]=new int[MAXSIZE][MAXSIZE];
int visited[]=new int [MAXSIZE];
Stack s=new Stack();
/*Function for Depth-First-Search */
void createGraph()
{
int n,i,j,parent,adj_parent,initial_node;
int ans=0,ans1=0;
System.out.print("¥nEnter total number elements in a Undirected
Graph :");
n=getNumber();
for ( i=1;i<=n;i++)
for( j=1;j<=n;j++)
adj[i][j]=0;
/*All graph nodes are unvisited, hence assigned zero to visited field of each
node */
for (int c=1;c<=50;c++)
visited[c]=0;
System.out.println("¥nEnter graph structure for BFS ");
do
{
System.out.print("¥nEnter parent node :");
parent=getNumber();
do
{
System.out.print("¥nEnter adjacent node for node "+parent+ " : ");
adj_parent=getNumber();
adj[parent][adj_parent]=1;
adj[adj_parent][parent]=1;
System.out.print("¥nContinue to add adjacent node for "+parent+"(1/0)?");
ans1= getNumber();
} while (ans1==1);
System.out.print("¥nContinue to add graph node?");
ans= getNumber();
}while (ans ==1);
System.out.print("¥nAdjacency matrix for your graph is :¥n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
System.out.print(" "+adj[i][j]);
System.out.print("¥n");
}
System.out.println("¥nYour Undirected Graph is :");
for (i=1;i<=n;i++)
{
System.out.print("¥nVertex "+i+"is connected to : ");
for (j=1;j<=n;j++)
{
if (adj[i][j]==1)
System.out.print(" "+j);
}
}
System.out.println("¥nEnter the initial node for BFS traversal:");
initial_node=getNumber();
DFS (initial_node, n);
}
void DFS (int initial_node,int n)
{
int u,i;
s.top = -1;
s.push(initial_node);
System.out.println("¥nDFS traversal for given graph is : ");
while(!s.isempty())
{
u=s.pop();
if(visited[u]==0)
{
System.out.print("¥n"+u);
visited[u]=1;
}
for (i=1;i<=n;i++)
{
if((adj[u][i]==1) && (visited[i]==0))
{
s.push(u);
visited[i]=1;
System.out.print(" "+i);
u = i;
}
}
}
}/* end of DFS function */
int getNumber() {
String str;
int ne=0;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(input);
try
{
str=in.readLine();
ne=Integer.parseInt(str);
}
catch(Exception e)
{
System.out.println("I/O Error");
}
return ne;
}
}
class Graph_DFS
{
public static void main(String args[])
{
Graph g=new Graph();
g.createGraph();
} /* end of program */
}
Output:
12. Write Java programs for implementing the following
sorting methods:
a) Bubble sort d) Merge sort g) Binary tree sort
b) Insertion sort e) Heap sort
c) Quick sort f) Radix sort
//Bubble Sort
import java.io.*;
class BubbleSort
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.print("¥n Unsorted array: ");
display( arr );
bubbleSort( arr );
System.out.print("¥n Sorted array: ");
display( arr );
}
static void bubbleSort(int[] a)
{
int i, pass, exch, n = a.length;
int tmp;
for( pass = 0; pass < n; pass++ )
{
exch = 0;
for( i = 0; i < n-pass-1; i++ )
if( ((Comparable)a[i]).compareTo(a[i+1]) > 0)
{
tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
exch++;
}
if( exch == 0 ) return;
}
}
static void display( int a[] )
{
for( int i = 0; i < a.length; i++ )
System.out.print( a[i] + " " );
}
}
OUTPUT:
//Insertion Sort
import java.io.*;
class InsertionSort
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.print("¥n Unsorted array: ");
display( arr );
insertionSort( arr );
System.out.print("¥n Sorted array: ");
display( arr );
}
static void insertionSort(int a[])
{
int i, j, n = a.length;
int item;
for( j = 1; j < n; j++ )
{
item = a[j];
i = j-1;
while( i >= 0 && ((Comparable)item).compareTo(a[i]) < 0)
{
a[i+1] = a[i];
i = i-1;
}
a[i+1] = item;
}
}
static void display( int a[] )
{
for( int i = 0; i < a.length; i++ )
System.out.print( a[i] + " " );
}
}
OUTPUT:
//Radix Sort
import java.io.*;
class RadixSort
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter maximum value");
int n1=Integer.parseInt(br1.readLine());
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.print("¥n Unsorted array: ");
display( arr );
radixSort(arr,n,n1);
System.out.print("¥n Sorted array: ");
display( arr );
}
static void radixSort(int[] arr, int radix, int maxDigits)
{
int d, j, k, m, divisor;
java.util.LinkedList[] queue = new
java.util.LinkedList[radix];
for( d = 0; d < radix; d++ )
queue[d] = new java.util.LinkedList();
divisor = 1;
for(d = 1; d <= maxDigits; d++)
{
for(j = 0; j < arr.length; j++)
{
m = (arr[j]/divisor) % radix;
queue[m].addLast(new Integer(arr[j]));
}
divisor = divisor*radix;
for(j = k = 0; j < radix; j++)
{
while( !queue[j].isEmpty())
arr[k++] = (Integer)queue[j].removeFirst();
}
}
}
static void display( int a[] )
{
for( int i = 0; i < a.length; i++ )
System.out.print( a[i] + " " );
}
}
OUTPUT: