Java Programs
Java Programs
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayListlinkedList = new ArrayList(10);
linkedList.initializeList();
linkedList.createList(4); // create 4 nodes
linkedList.display(); // print the list
System.out.print("InsertFirst 55:");
linkedList.insertFirst(55);
linkedList.display();
System.out.print("Insert 66 after 33:");
linkedList.insertAfter(66, 33); // insert 66 after 33
linkedList.display();
Object item = linkedList.deleteFirst(); System.out.println("Deleted node: " + item);
linkedList.display();
System.out.print("InsertFirst 77:");
linkedList.insertFirst(77);
linkedList.display();
item = linkedList.deleteAfter(22); // delete node after node 22
System.out.println("Deleted node: " + item);
linkedList.display();
System.out.println("size(): " + linkedList.size());
}
}
Output:
E:\javac ArrayListDemo.java
E:\java ArrayListDemo
List: [ 11 22 33 44 ]
InsertFirst 55:
List: [ 55 11 22 33 44 ]
Insert 66 after 33:
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
1(b)
class LinkedList implements List
{
class Node
{ Object data; // data item
Node next; // refers to next node in the list
Node( Object d ) // constructor
{ data = d; } // ‘next’ is automatically set to null
}
Node head; // head refers to first node
Node p; // p refers to current node
int count; // current number of nodes
public void createList(int n) // create 'n' nodes
{
p = new Node(11); // create first node
head = p; // assign mem. address of 'p' to 'head'
for( inti = 1; i< n; i++ ) // create 'n-1' nodes
p = p.next = new Node(11 + 11*i);
count = n;
}
public void insertFirst(Object item) // insert at the beginning of list
{
p = new Node(item); // create new node
p.next = head; // new node refers to old head
head = p; // new head refers to new node
count++;
}
public void insertAfter(Object item,Object key)
{
p = find(key); // get “location of key item”
if( p == null )
System.out.println(key + " key is not found");
else
{ Node q = new Node(item); // create new node
q.next = p.next; // new node next refers to p.next
p.next = q; // p.next refers to new node
count++;
}
}
public Node find(Object key)
{
p = head;
while( p != null ) // start at beginning of list until end of list
{
if( p.data == key ) return p; // if found, return key address
p = p.next; // move to next node
}
return null; // if key search is unsuccessful, return null
}
public Object deleteFirst() // delete first node
{
if( isEmpty() )
{ System.out.println("List is empty: no deletion");
return null;
}
Node tmp = head; // tmp saves reference to head
head = tmp.next;
count--;
return tmp.data;
}
public Object deleteAfter(Object key) // delete node after key item
{ p = find(key); // p = “location of key node”
if( p == null )
{ System.out.println(key + " key is not found");
return null;
}
if( p.next == null ) // if(there is no node after key node)
{ System.out.println("No deletion");
return null;
}
else
{ Nodetmp = p.next; // save node after key node
p.next = tmp.next; // point to next of node deleted
count--;
return tmp.data; // return deleted node
}
}
public void displayList()
{ p = head; // assign mem. address of 'head' to 'p'
System.out.print("\nLinked List: ");
while( p != null ) // start at beginning of list until end of list
{ System.out.print(p.data + " -> "); // print data
p = p.next; // move to next node
}
System.out.println(p); // prints 'null'
}
public booleanisEmpty() // true if list is empty
{ return (head == null); }
public int size()
{ return count; }
} // end of LinkeList class
class LinkedListDemo
{ public static void main(String[] args)
{ LinkedList list = new LinkedList(); // create list object
list.createList(4); // create 4 nodes
list.displayList();
list.insertFirst(55); // insert 55 as first node
list.displayList();
list.insertAfter(66, 33); // insert 66 after 33
list.displayList();
Object item = list.deleteFirst(); // delete first node
if( item != null )
{ System.out.println("deleteFirst(): " + item);
list.displayList();
}
item = list.deleteAfter(22); // delete a node after node(22)
if( item != null )
{ System.out.println("deleteAfter(22): " + item);
list.displayList();
}
System.out.println("size(): " + list.size());
}
}
Output:
E:\javac LinkedListDemo.java
E:\java LinkedListDemo
deleteFirst(): 55
deleteAfter(22): 33
size(): 4
//2(a)
public interface Stack
{
public void push(Object ob);
public Object pop();
public Object peek();
public boolean isEmpty();
public int size();
}
class ArrayStackDemo
{
public static void main(String[] args)
{
ArrayStack stk = new ArrayStack(4); // create stack of size 4
Object item;
stk.push('A'); // push 3 items onto stack
stk.push('B');
stk.push('C');
System.out.println("size(): "+ stk.size());
item = stk.pop(); // delete item
System.out.println(item + " is deleted");
stk.push('D'); // add three more items to the stack
stk.push('E');
stk.push('F');
System.out.println(stk.pop() + " is deleted");
stk.push('G'); // push one item
item = stk.peek(); // get top item from the stack
System.out.println(item + " is on top of stack");
}
}
Output :
E:\javac Stack.java
E:\javac ArrayStackDemo.java
E:\java ArrayStackDemo
size(): 3
C is deleted
Stack is full
E is deleted
G is on top of stack
2(b)
Public interface Queue
{
public void insert(Object ob);
public Object remove();
public Object peek();
public booleanisEmpty();
public int size();
}
class ArrayQueue implements Queue
{ private int maxSize; // maximum queue size
private Object[] que; // que is an array
private int front;
private int rear;
private int count; // count of items in queue (queue size)
public ArrayQueue(int s) // constructor
{ maxSize = s;
que = new Object[maxSize];
front = rear = -1;
count = 0;
}
public void insert(Object item) // add item at rear of queue
{
if( count == maxSize )
{ System.out.println("Queue is Full"); return; }
if(rear == maxSize-1 || rear == -1)
{ que[0] = item;
rear = 0;
if( front == -1) front = 0;
}
else que[++rear] = item;
count++; // update queue size
}
public Object remove() // delete item from front of queue
{
if( isEmpty() )
{System.out.println("Queue is Empty"); return 0; }
Object tmp = que[front]; // save item to be deleted
que[front] = null; // make deleted item’s cell empty
if( front == rear )
rear = front = -1;
else if( front == maxSize-1 ) front = 0;
else front++;
count--; // less one item from the queue size
return tmp;
}
public Object peek() // peek at front of the queue
{ return que[front]; }
public booleanisEmpty() // true if the queue is empty
{ return (count == 0); }
public int size() // current number of items in the queue
{ return count; }
public void displayAll()
{
System.out.print("Queue: ");
for( inti = 0; i<maxSize; i++ )
System.out.print( que[i] + " ");
System.out.println();
}
}
class QueueDemo
{
public static void main(String[] args)
{
/* queue holds a max of 5 items */
ArrayQueue q = new ArrayQueue(5);
Object item;
q.insert('A'); q.insert('B'); q.insert('C'); q.displayAll();
item = q.remove(); // delete item
System.out.println(item + " is deleted");
item = q.remove();
System.out.println(item + " is deleted");
q.displayAll();
q.insert('D'); // insert 3 more items
q.insert('E');
q.insert('F');
q.displayAll();
item = q.remove();
System.out.println(item + " is deleted");
q.displayAll();
System.out.println("peek(): " + q.peek());
q.insert('G');
q.displayAll();
System.out.println("Queue size: " + q.size());
}
}
Output:
E:\javac Queue.java
E:\javac QueueDemo.java
E:\java QueueDemo
Queue: A B C null null
A is deleted
B is deleted
Queue: null null C null null
Queue: F null C D E
C is deleted
Queue: F null null D E
peek(): D
Queue: F G null D E
Queue size: 4
Program 3(a):Infix to postfix conversion
import java.util.Scanner;
class InfixToPostfix
{
java.util.Stack<Character>stk =
new java.util.Stack<Character>();
public String toPostfix(String infix)
{
infix = "(" + infix + ")"; // enclose infix expr within parentheses
String postfix = "";
/* scan the infix char-by-char until end of string is reached */
for( inti=0; i<infix.length(); i++)
{
char ch, item;
ch = infix.charAt(i);
if( isOperand(ch) ) // if(ch is an operand), then
postfix = postfix + ch; // append ch to postfix string
class InfixToPostfixDemo
{
public static void main(String args[])
{
E:\>javac EvaluatePostfixExpression.java
E:\>java EvaluatePostfixExpression
E:\javac LinkedPriorityQueueDemo.java
E:\java LinkedPriorityQueueDemo
delete():Kim(1)
class BST
{
// Function to perform inorder traversal on the tree
public static void inorder(Node root)
{
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
// Function to construct balanced BST from the given sorted array
public static Node convert(int[] keys, int low, int high, Node root)
{
// base case
if (low > high) {
return root;
}
// find the middle element of the current range
int mid = (low + high) / 2;
// construct a new node from the middle element and assign it to the root
root = new Node(keys[mid]);
// left subtree of the root will be formed by keys less than middle element
root.left = convert(keys, low, mid - 1, root.left);
// right subtree of the root will be formed by keys more than the
// middle element
root.right = convert(keys, mid + 1, high, root.right);
return root;
}
// Function to construct balanced BST from the given unsorted array
public static Node convert(int[] keys)
{
// sort the keys first
Arrays.sort(keys);
// construct a balanced BST and return the root node of the tree
return convert(keys, 0, keys.length - 1, null);
}
public static void main(String[] args)
{
// input keys
int[] keys = { 15, 10, 20, 8, 12, 16, 25 };
// construct a balanced binary search tree
Node root = convert(keys);
// print the keys in an inorder fashion
inorder(root);
}
}
Output:
E:\>javac BST.java
E:\>java BST
8 10 12 15 16 20 25
//Program 5(b):Delete an element from a binary search tree
class Node
{
int data;
Node left = null, right = null;
Node(int data) {
this.data = data;
}
}
class BSTDel
{
// Function to perform inorder traversal on the BST
public static void inorder(Node root)
{
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
// Helper function to find minimum value node in the subtree rooted at `curr`
public static Node getMinimumKey(Node curr)
{
while (curr.left != null) {
curr = curr.left;
}
return curr;
}
// Recursive function to insert a key into a BST
public static Node insert(Node root, int key)
{
// if the root is null, create a new node and return it
if (root == null) {
return new Node(key);
}
// if the given key is less than the root node, recur for the left subtree
if (key <root.data) {
root.left = insert(root.left, key);
}
// if the given key is more than the root node, recur for the right subtree
else {
root.right = insert(root.right, key);
}
return root;
}
// Function to delete a node from a BST
public static Node deleteNode(Node root, int key)
{
// pointer to store the parent of the current node
Node parent = null;
// start with the root node
Node curr = root;
E:\>javac BSTDel.java
E:\>java BSTDel
8 10 12 15 20
Program 5(c):Search for a key element in a binary search
class Node
{
int data;
Node left = null, right = null;
Node(int data) {
this.data = data;
}
}
class BSTsearch
{
// Recursive function to insert a key into a BST
public static Node insert(Node root, int key)
{
// if the root is null, create a new node and return it
if (root == null) {
return new Node(key);
}
// if the given key is less than the root node, recur for the left subtree
if (key <root.data) {
root.left = insert(root.left, key);
}
// if the given key is more than the root node, recur for the right subtree
else {
root.right = insert(root.right, key);
}
return root;
}
// Recursive function to search in a given BST
public static void search(Node root, int key, Node parent)
{
// if the key is not present in the key
if (root == null)
{
System.out.print("Key Not found");
return;
}
// if the key is found
if (root.data == key)
{
if (parent == null) {
System.out.print("The node with key " + key + " is root node");
}
else if (key <parent.data)
{
System.out.print("The given key is the left node of the node " +
"with key " + parent.data);
}
else {
System.out.print("The given key is the right node of the node " +
"with key " + parent.data);
}
return;
}
// if the given key is less than the root node, recur for the left subtree;
// otherwise, recur for the right subtree
if (key <root.data) {
search(root.left, key, root);
}
else {
search(root.right, key, root);
}
}
public static void main(String[] args)
{
int[] keys = { 15, 10, 20, 8, 12, 16, 25 };
Node root = null;
for (int key: keys) {
root = insert(root, key);
}
search(root, 25, null);
}
}
Output:
E:\>javac BSTsearch.java
E:\>java BSTsearch
The given key is the right node of the node with key 20
Program 6:AVL tree-Insertion and Deletion
// Create node
class Node {
int item, height;
Node left, right;
Node(int d) {
item = d;
height = 1;
}
}
// Tree class
class AVLTree {
Node root;
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
return x;
}
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = max(height(x.left), height(x.right)) + 1;
y.height = max(height(y.left), height(y.right)) + 1;
return y;
}
// Get balance factor of a node
int getBalanceFactor(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
// Insert a node
Node insertNode(Node node, int item) {
// Find the position and insert the node
if (node == null)
return (new Node(item));
if (item <node.item)
node.left = insertNode(node.left, item);
else if (item >node.item)
node.right = insertNode(node.right, item);
else
return node;
// Update the balance factor of each node
// And, balance the tree
node.height = 1 + max(height(node.left), height(node.right));
int balanceFactor = getBalanceFactor(node);
if (balanceFactor> 1) {
if (item <node.left.item) {
return rightRotate(node);
} else if (item >node.left.item) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
}
if (balanceFactor< -1) {
if (item >node.right.item) {
return leftRotate(node);
} else if (item <node.right.item) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
}
return node;
}
Node nodeWithMimumValue(Node node) {
Node current = node;
while (current.left != null)
current = current.left;
return current;
}
// Delete a node
Node deleteNode(Node root, int item) {
// Find the node to be deleted and remove it
if (root == null)
return root;
if (item <root.item)
root.left = deleteNode(root.left, item);
else if (item >root.item)
root.right = deleteNode(root.right, item);
else {
if ((root.left == null) || (root.right == null)) {
Node temp = null;
if (temp == root.left)
temp = root.right;
else
temp = root.left;
if (temp == null) {
temp = root;
root = null;
} else
root = temp;
} else {
Node temp = nodeWithMimumValue(root.right);
root.item = temp.item;
root.right = deleteNode(root.right, temp.item);
}
}
if (root == null)
return root;
// Update the balance factor of each node and balance the tree
root.height = max(height(root.left), height(root.right)) + 1;
int balanceFactor = getBalanceFactor(root);
if (balanceFactor> 1) {
if (getBalanceFactor(root.left) >= 0) {
return rightRotate(root);
} else {
root.left = leftRotate(root.left);
return rightRotate(root);
}
}
if (balanceFactor< -1) {
if (getBalanceFactor(root.right) <= 0) {
return leftRotate(root);
} else {
root.right = rightRotate(root.right);
return leftRotate(root);
}
}
return root;
}
E:\>javac AVLTree.java
E:\>java AVLTree
R----33
L----13
| L----9
| | L----8
| | R----11
| R----21
R----53
R----61
After Deletion:
R----33
L----9
| L----8
| R----21
| L----11
R----53
R----61
//Breadth First Search for a given graph
class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}
class Graph
{ int size;
Node adjList[];
int mark[];
Graph(int n) // constructor
{ size = n;
adjList = new Node[size];
mark = new int[size];
}
public void createAdjList(int a[][]) // create adjacent lists
{ Node p; int i, k;
for( i = 0; i< size; i++ )
{ p = adjList[i] = new Node(i);
for( k = 0; k < size; k++ )
{ if( a[i][k] == 1 )
{ p.next = new Node(k);
p = p.next;
}
} // end of inner for-loop
} // end of outer for-loop
} // end of createAdjList()
public void bfs(int head)
{ int v; Node adj;
Queue q = new Queue(size);
v = head;
mark[v] = 1;
System.out.print(v + " ");
q.qinsert(v);
while( !q.IsEmpty() ) // while(queue not empty)
{
v = q.qdelete();
adj = adjList[v];
while( adj != null )
{ v = adj.label;
if( mark[v] == 0 )
{ q.qinsert(v);
mark[v] = 1;
System.out.print(v + " ");
}
adj = adj.next;
}
}
}
} // end of Graph class
class Queue
{ private int maxSize; // max queue size
private int[] que; // que is an array of integers
private int front;
private int rear;
private int count; // count of items in queue
public Queue(int s) // constructor
{ maxSize = s;
que = new int[maxSize];
front = rear = -1;
}
public void qinsert(int item)
{ if( rear == maxSize-1 )
System.out.println("Queue is Full");
else { rear = rear + 1;
que[rear] = item;
if( front == -1 ) front = 0;
}
}
public int qdelete()
{ int item;
if( IsEmpty() )
{ System.out.println("\n Queue is Empty");
return(-1);
}
item = que[front];
if( front == rear ) front = rear = -1;
else front = front+1;
return(item);
}
public booleanIsEmpty()
{ return( front == -1 ); }
} // end of Queue class
class BfsDemo
{ public static void main(String[] args)
{ Graph g = new Graph(5);
int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},
{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.bfs(0);
}
}
Output:
E:\>javac BfsDemo.java
E:\>java BfsDemo
01342
//DFS
class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}
class Graph
{ int size;
Node adjList[];
int mark[];
Graph(int n) // constructor
{ size = n;
adjList = new Node[size];
mark = new int[size]; // elements of mark are initialized to 0
}
public void createAdjList(int a[][]) // create adjacent lists
{
Node p; int i, k;
for( i = 0; i< size; i++ )
{ p = adjList[i] = new Node(i); //create first node of ith adj. list
for( k = 0; k < size; k++ )
{ if( a[i][k] == 1 )
{ p.next = new Node(k); // create next node of ith adj. list
p = p.next;
}
}
}
}
public void dfs(int head) // recursive depth-first search
{ Node w; int v;
mark[head] = 1;
System.out.print( head + " ");
w = adjList[head];
while( w != null)
{ v = w.label;
if( mark[v] == 0 ) dfs(v);
w = w.next;
}
}
}
class DfsDemo
{
public static void main(String[] args)
{
Graph g = new Graph(5); // graph is created with 5 nodes
int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},
{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.dfs(0); // starting node to dfs is0 (i.e., A)
}
}
Output:
E:\javac DfsDemo.java
E:\java DfsDemo
01234
//9(a)Linear Search
class LinearSearchDemo
if( linearSearch() )
else
static booleanlinearSearch()
return false;
}
E:\javac LinearSearchDemo.java
E:\java LinearSearchDemo
E:\java BinarySearchDemo
import java.util.Scanner;
public class BubbleSortDemo
{
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i< n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] >arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;}
}
}
}
public static void main(String[] args)
{
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++)
//reading array elements from the user
arr[i]=sc.nextInt();
System.out.println("Array Before Bubble Sort");
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("Array After Bubble Sort");
for(int i=0; i<arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Output:
E:\>javac BubbleSortDemo.java
E:\>java BubbleSortDemo
54
67
14
25
87
29
54 67 14 25 87 29
14 25 29 54 67 87
//Program 10(b):Selection Sort
import java.util.Scanner;
class SelectionSortDemo
{
public static void main(String[] args)
{
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++)
{
//reading array elements from the user
arr[i]=sc.nextInt(); }
System.out.print("\n Unsorted array: ");
display( arr );
selectionSort( arr );
System.out.print("\n Sorted array: ");
display( arr ); }
static void selectionSort( intarr[] )
{
int n = arr.length;
for( int pass = 0; pass < n-1; pass++ )
{
int min = pass;
for( inti = pass+1; i< n; i++ )
if( arr[i] <arr[min] ) min = i;
if( min != pass )
{
int tmp = arr[min];
arr[min] = arr[pass];
arr[pass] = tmp; } } }
static void display( intarr[] )
{
for( inti = 0; i<arr.length; i++ )
System.out.print( arr[i] + " " ); } }
Output:
E:\>javac SelectionSortDemo.java
E:\>java SelectionSortDemo
21
34
65
23
45
50
Unsorted array: 21 34 65 23 45 50
Sorted array: 21 23 34 45 50 65
//Program 10(c): Insertion Sort
import java.util.Scanner;
public class InsertionSortDemo {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i> -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
E:\>javac InsertionSortDemo.java
E:\>java InsertionSortDemo
12
54
34
23
10
87
12 54 34 23 10 87
10 12 23 34 54 87
//Program 10(d):Radix Sort
import java.util.Scanner;
class RadixSortDemo
{
public static void main(String[] args)
{
//int[] a = { 3305, 99, 52367, 125, 10, 12345, 7, 35, 7509, 3, 345 };
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++)
{
//reading array elements from the user
arr[i]=sc.nextInt();
}
radixSort(arr, 10, 5);
System.out.println("Sorted list: ");
for(int i = 0; i< n; i++ )
System.out.print( arr[i] + " ");
}
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++) // Pass: 1, 2, 3, . . .
{
for(j = 0; j <arr.length; j++)
{
m = (arr[j]/divisor) % radix;
queue[m].addLast(new Integer(arr[j]));
}
divisor = divisor*radix; // 1, 10, 100, ...
for(j = k = 0; j < radix; j++)
{
while( !queue[j].isEmpty())
arr[k++] = (Integer)queue[j].removeFirst();
}
}
}
}
Output:
E:\>javac RadixSortDemo.java
E:\>java RadixSortDemo
34
23
14
29
45
15
30
21
76
54
Sorted list:
14 15 21 23 29 30 34 45 54 76