0% found this document useful (0 votes)
5 views61 pages

DS Lab Programs

Uploaded by

vamsi.d124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views61 pages

DS Lab Programs

Uploaded by

vamsi.d124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 61

Array of Operations

import java.io.*;
import java.util.Scanner;
class ArrayOperation
{
private int[] theArray;
private int capacity;
private int size;
public ArrayOperation()
{
capacity=30;
size=1;
theArray=new int[capacity];
}
public void insertAtLast(int ele)
{
if(size==capacity)
{
return;
}
else
{
theArray[size++]=ele;
}
}
public void print()
{
for(int i=1;i<size;i++)
{
System.out.print(" "+theArray[i]+" ");
}
}
public void delete(int pos)
{
int i=size;
while(pos<i)
{
theArray[pos]=theArray[pos+1];
pos++;
}
size=size-1;
}
public void deleteAtLast()
{
int del_ele=theArray[size-1];
System.out.println("Last element in the array is "+del_ele+"deleted");
size--;
}
public void addAtMiddle(int ele,int pos)
{
int i=size;
while(i>=pos)
{
theArray[i+1]=theArray[i];
i--;
}
size++;
theArray[pos]=ele;
}
public void sort()
{
for(int i=1;i<size-1;i++)
for(int j=i+1;j<size;j++)
{
if(theArray[i]>theArray[j])
{
int temp=theArray[i];
theArray[i]=theArray[j];
theArray[j]=temp;
}
}
}
public void search(int ele)
{
boolean flag=true;
for(int i=1;i<size;i++)
if(theArray[i]==ele)
{
System.out.println("\n\tsearch is successfull");
System.out.println("\n\tElement found at\t "+i+"\t location");
flag=false;
break;
}
if(flag)
{
System.out.println("\n\tSearch is unsuccessfull");
System.out.println("\n\tElement is not there in an array");
}
}
}
class ArrayOperationImplementation
{
public static void main(String[] args)
{
ArrayOperation ao=new ArrayOperation();
int ele,pos;
while(true)
{
Scanner s=new Scanner(System.in);
System.out.println("*******MENU FOR ARRAY OF
OPERATION*******");
System.out.println("\n \t 1. Insert Element At Last \n \t 2. Insert Element
At Middle \n \t 3. Delete At Last \n \t 4. Delete Element At Middle \n \t 5. Sorting \n \t 6.
Searching \t\n \t 7. Traversing");
System.out.println("Enter your choice");
int ch=s.nextInt();
switch(ch)
{

case 1: System.out.println("Please Enter the element to be


inserting");
ele=s.nextInt();
ao.insertAtLast(ele);
break;
case 2: System.out.println("Please enter the element to be
inserting");
ele=s.nextInt();
System.out.println("Please enter the position where element
is to be inserted");
pos=s.nextInt();
ao.addAtMiddle(ele,pos);
break;
case 3:
ao.deleteAtLast();
break;
case 4: System.out.println("\n \tPlease enter pos to be delete the
element");
pos=s.nextInt();
break;
case 5:
System.out.println("\n \tElements in the array are sorted,
please select traverse to see the sorted elements::");
ao.sort();
break;
case 6:
System.out.println("\n \tEnter the element to be search");
int ser_ele=s.nextInt();
ao.search(ser_ele);
break;
case 7:
System.out.println("\n \tThe elements in the array are:");
ao.print();
break;
default:
System.out.println("\n \tInvalid Selection");
}
System.out.println("\n \t Do you want to continue");
char say=s.next().charAt(0);
if(say=='N'||say=='n')
{
System.out.println("Thank you and my work is over...");
break;
}
}
}
}
Output:

E:\ java ArrayOperationImplementation 7. Traversing


Enter your choice
*******MENU FOR ARRAY OF 7
OPERATION*******
The elements in the array are:
1. Insert Element At Last 10 89
2. Insert Element At Middle Do you want to continue
3. Delete At Last y
4. Delete Element At Middle *******MENU FOR ARRAY OF
5. Sorting OPERATION*******
6. Searching
7. Traversing 1. Insert Element At Last
Enter your choice 2. Insert Element At Middle
1 3. Delete At Last
Please Enter the element to be inserting 4. Delete Element At Middle
10 5. Sorting
6. Searching
Do you want to continue 7. Traversing
y Enter your choice
*******MENU FOR ARRAY OF 2
OPERATION******* Please enter the element to be inserting
6
1. Insert Element At Last Please enter the position where element is to
2. Insert Element At Middle be inserted
3. Delete At Last 1
4. Delete Element At Middle
5. Sorting Do you want to continue
6. Searching y
7. Traversing *******MENU FOR ARRAY OF
Enter your choice OPERATION*******
1
Please Enter the element to be inserting 1. Insert Element At Last
89 2. Insert Element At Middle
3. Delete At Last
Do you want to continue 4. Delete Element At Middle
y 5. Sorting
*******MENU FOR ARRAY OF 6. Searching
OPERATION******* 7. Traversing
Enter your choice
1. Insert Element At Last 7
2. Insert Element At Middle
3. Delete At Last The elements in the array are:
4. Delete Element At Middle 6 10 89
5. Sorting Do you want to continue
6. Searching 3
*******MENU FOR ARRAY OF Elements in the array are sorted, please
OPERATION******* select traverse to see the sort
ed elements::
1. Insert Element At Last
2. Insert Element At Middle Do you want to continue
3. Delete At Last y
4. Delete Element At Middle *******MENU FOR ARRAY OF
5. Sorting OPERATION*******
6. Searching
7. Traversing 1. Insert Element At Last
Enter your choice 2. Insert Element At Middle
7 3. Delete At Last
4. Delete Element At Middle
The elements in the array are: 5. Sorting
6 10 89 6. Searching
Do you want to continue 7. Traversing
y Enter your choice
*******MENU FOR ARRAY OF 7
OPERATION*******
The elements in the array are:
1. Insert Element At Last 6 10
2. Insert Element At Middle Do you want to continue
3. Delete At Last 6
4. Delete Element At Middle *******MENU FOR ARRAY OF
5. Sorting OPERATION*******
6. Searching
7. Traversing 1. Insert Element At Last
Enter your choice 2. Insert Element At Middle
3 3. Delete At Last
Last element in the array is 89deleted 4. Delete Element At Middle
5. Sorting
Do you want to continue 6. Searching
y 7. Traversing
*******MENU FOR ARRAY OF Enter your choice
OPERATION******* 6

1. Insert Element At Last Enter the element to be search


2. Insert Element At Middle 6
3. Delete At Last
4. Delete Element At Middle search is successfull
5. Sorting
6. Searching Element found at 1 location
7. Traversing
Enter your choice Do you want to continue
5 y
*******MENU FOR ARRAY OF
OPERATION******* Enter the element to be search
100
1. Insert Element At Last
2. Insert Element At Middle Search is unsuccessfull
3. Delete At Last
4. Delete Element At Middle Element is not there in an array
5. Sorting
6. Searching Do you want to continue
7. Traversing n
Enter your choice Thank you and my work is over...
6
Single Linked List
import java.util.Scanner;
class Link
{
private int data;
public Link link;
public Link(int data)
{
this.data=data;
link=null;
}
public Link(int data,Link link)
{
this.data=data;
this.link=link;
}
public String Data()
{
return data+"-->";
}
}
class SingleLinkedList
{
private Link head;
private int size;
public SingleLinkedList()
{
head=null;
size=0;
}
public boolean isEmpty()
{
return head==null;
}
public void addFront(int data)
{
if(head==null)
head=new Link(data,null);
else
{
Link newLink=new Link(data,head);
newLink.link=head;
head=newLink;
}
size++;
}
public void addLast(int data)
{
if(head==null)
head=new Link(data,null);
else
{
Link current=head;
while(current.link!=null)
current=current.link;
Link newLink=new Link(data,null);
current.link=newLink;
}
size++;
}
public void addAny(int data,int pos)
{
if(head==null)
head=new Link(data,null);
Link current=head;
for(int i=1;i<pos;i++)
current=current.link;
Link newLink=new Link(data,null);
newLink.link=current.link;
current.link=newLink;
size++;
}
public void deleteAny(int pos)
{
if(head==null)
return;
Link current=head;
for(int i=1;i<pos;i++)
current=current.link;
current.link=current.link.link;
size--;
}
public void deleteFront()
{
if(head==null)
System.out.println("List is Empty");
else
{
Link del=head;
head=del.link;
}
size--;
}
public void deleteLast()
{
if(head==null)
System.out.println("List is empty");
if(head.link==null)
{
head=null;
size--;
}
Link current=head;
while(current.link.link!=null)
current=current.link;
current.link=null;
size--;
}
public void print()
{
if(head==null)
System.out.println("List is empty...");
Link current=head;
while(current.link!=null)
{
System.out.print(current.Data());
current=current.link;
}
System.out.print(current.Data()+"null");
System.out.println();
}
public static void main(String...args)
{
Scanner sc=new Scanner(System.in);
SingleLinkedList s=new SingleLinkedList();
int info,pos;
while(true)
{
System.out.println("........Menu........");
System.out.println("\n\t\t 1. Add Node At Front \n\t\t 2. Add Node At Rear \n\t\t 3. Remove
Node At Front \n\t\t 4. Remove At Last \n\t\t 5. Add Node At Position \n\t\t 6. Remove Node At
Any pos\n\t\t 7. Display elements in list \n\n");
System.out.println("\n Enter your choice\n");
int choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter data part to a node");
info=sc.nextInt();
s.addFront(info);
break;
case 2: System.out.println("Enter data part to a node");
info=sc.nextInt();
s.addLast(info);
break;
case 3: s.deleteFront();
System.out.println("\n Front node is deleted");
break;
case 4: s.deleteLast();
System.out.println("\n Last node is deleted");
break;
case 5: System.out.println("Enter the data part to the node");
info=sc.nextInt();
System.out.println("Enter the postion where you insert a node in list");
pos=sc.nextInt();
s.addAny(info,pos);
break;
case 6: System.out.println("Enter the postion where you delete a node in list");
pos=sc.nextInt();
s.deleteAny(pos);
break;
case 7: s.print();
break;
default: System.out.println("You are selection is not there in menu\n");
}
System.out.println("\n \n Do you want to contine....\n Press y or Y for(Yes)|| n or N for(No)");
char ch=sc.next().charAt(0);
if(ch=='n'||ch=='N')
{
System.out.println("\n\n Thank you see you again..\n\n");
break;
}
}
}
}
Output:
E:\ javac SingleLinkedList Do you want to contine....
E:\ java SingleLinkedList Press y or Y for(Yes)|| n or N for(No)
y
........Menu........ ........Menu........
1. Add Node At Front
2. Add Node At Rear 1. Add Node At Front
3. Remove Node At Front 2. Add Node At Rear
4. Remove At Last 3. Remove Node At Front
5. Add Node At Position 4. Remove At Last
6. Remove Node At Any pos 5. Add Node At Position
7. Display elements in list 6. Remove Node At Any pos
Enter your choice 7. Display elements in list
1 Enter your choice
Enter data part to a node 7
10 66-->10-->20-->null
Do you want to contine.... Do you want to contine....
Press y or Y for(Yes)|| n or N for(No) Press y or Y for(Yes)|| n or N for(No)
y y
........Menu........ ........Menu........
1. Add Node At Front
2. Add Node At Rear 1. Add Node At Front
3. Remove Node At Front 2. Add Node At Rear
4. Remove At Last 3. Remove Node At Front
5. Add Node At Position 4. Remove At Last
6. Remove Node At Any pos 5. Add Node At Position
7. Display elements in list 6. Remove Node At Any pos
Enter your choice 7. Display elements in list
2 Enter your choice
Enter data part to a node 3
20 Front node is deleted
Do you want to contine.... Do you want to contine....
Press y or Y for(Yes)|| n or N for(No) Press y or Y for(Yes)|| n or N for(No)
y y
........Menu........ ........Menu........
1. Add Node At Front 1. Add Node At Front
2. Add Node At Rear 2. Add Node At Rear
3. Remove Node At Front 3. Remove Node At Front
4. Remove At Last 4. Remove At Last
5. Add Node At Position 5. Add Node At Position
6. Remove Node At Any pos 6. Remove Node At Any pos
7. Display elements in list 7. Display elements in list
Enter your choice Enter your choice
1 7
Enter data part to a node 10-->20-->null
66 Do you want to contine....
Press y or Y for(Yes)|| n or N for(No) Press y or Y for(Yes)|| n or N for(No)
y y
........Menu........ ........Menu........

1. Add Node At Front 1. Add Node At Front


2. Add Node At Rear 2. Add Node At Rear
3. Remove Node At Front 3. Remove Node At Front
4. Remove At Last 4. Remove At Last
5. Add Node At Position 5. Add Node At Position
6. Remove Node At Any pos 6. Remove Node At Any pos
7. Display elements in list 7. Display elements in list
Enter your choice Enter your choice
5 7
Enter the data part to the node 10-->89-->20-->null
89 Do you want to contine....
Enter the postion where you insert a node in Press y or Y for(Yes)|| n or N for(No)
list n
1 Thank you see you again..
Do you want to contine....
Stack Implementation using Arrays

Source Code:

class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}
}

// Driver code
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
}
}
Output : E:\ javac Stack.java
E:\ java Stack

10 pushed into stack


20 pushed into stack
30 pushed into stack
30 popped from stack
Stack by using List

import java.io.*;
import java.util.Scanner;
class Stack
{
int item;
Stack next;
public Stack()
{
this.item=0;
this.next=null;
}
public Stack(int item)
{
this.item=item;
this.next=next;
}
}

class StackImpleByList
{
Stack head,top;
int size;
public StackImpleByList()
{
this.head=null;
this.size=0;
}
public void push(int item)
{
Stack newItem=new Stack(item);
if(head==null)
{
head=newItem;
top=head;
size++;
}
else
{
Stack current=head;
while(current.next!=null)
current=current.next;
current.next=newItem;
top=current.next;
size++;
}
}
public void pop()
{
if(head==null)
System.out.println("Stack is under flow");
else
{
Stack current=head;
while(current.next.next!=null)
current=current.next;
current.next=null;
top=current;
size--;
}
}
public void print()
{
if(head==null)
System.out.println("Stack is empty");
else
{
Stack current=head;
while(current.next!=null)
{
System.out.println(" "+current.item+ " ");
current=current.next;
}
System.out.println(" "+current.item+ " ");
}
}
public int getStackSize()
{
return size;
}
public void peep()
{
System.out.println("Item on top of the stack is"+top.item);
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
StackImpleByList sbi=new StackImpleByList();
while(true)
{
System.out.println(".....Menu....");
System.out.println("\n \n \t 1. push (Adding the element into stack at top position \n \n \t 2. pop
(Deleting a element from stack at top of the stack) \n \n \t 3. Peep (Accessing the top element of
stack) \n \n \t 4. Print Stack \n \n \t 5. Get size of the stack");
System.out.println("\n \n \t Enter your choice");
int choice=s.nextInt();
switch(choice)
{
case 1: int ele;
System.out.println("Enter the item to be added into the queue");
ele=s.nextInt();
sbi.push(ele);
break;
case 2:
sbi.pop();
break;

case 3:
sbi.peep();
break;

case 4:
System.out.println("Stack items are:");
sbi.print();
break;

case 5:
System.out.println("Size of the stack is::"+sbi.getStackSize());
break;
default: System.out.println("Wrong choice");
}
System.out.println("\n\n \t Do you want continue...");
char ch=s.next().charAt(0);
if(ch=='N' || ch=='n')
{
System.out.println("\n \n \t Thank you and see you again...");
break;
}
}
}
}
Output:

E:\ javac Stack.java 5. Get size of the stack


Enter your choice
E:\ javac StackImpleByList.java 1
Enter the item to be added into the queue
E:\ java StackImpleByList 89
.....Menu.... Do you want continue...
1. push (Adding the element into stack y
at top position .....Menu....
2. pop (Deleting a element from stack
at top of the stack)
3. Peep (Accessing the top element of 1. push (Adding the element into stack
stack) at top position
4. Print Stack 2. pop (Deleting a element from stack
5. Get size of the stack at top of the stack)
3. Peep (Accessing the top element of
Enter your choice stack)
1 4. Print Stack
Enter the item to be added into the queue 5. Get size of the stack
10 Enter your choice
Do you want continue... 4
y Stack items are:
.....Menu.... 10
1. push (Adding the element into stack 23
at top position 89
2. pop (Deleting a element from stack
at top of the stack)
3. Peep (Accessing the top element of Do you want continue...
stack) y
4. Print Stack .....Menu....
5. Get size of the stack 1. push (Adding the element into stack
Enter your choice at top position
1 2. pop (Deleting a element from stack
Enter the item to be added into the queue at top of the stack)
23 3. Peep (Accessing the top element of
Do you want continue... stack)
y 4. Print Stack
.....Menu.... 5. Get size of the stack
1. push (Adding the element into stack Enter your choice
at top position 2
2. pop (Deleting a element from stack Do you want continue...
at top of the stack) y
3. Peep (Accessing the top element of .....Menu....
stack) 1. push (Adding the element into stack
4. Print Stack at top position
2. pop (Deleting a element from stack 1. push (Adding the element into stack
at top of the stack) at top position
3. Peep (Accessing the top element of 2. pop (Deleting a element from stack
stack) at top of the stack)
4. Print Stack 3. Peep (Accessing the top element of
5. Get size of the stack stack)
Enter your choice 4. Print Stack
4
Stack items are: 5. Get size of the stack
10 Enter your choice
23 3
Do you want continue... Item on top of the stack is23
y
.....Menu.... Do you want continue...
n
Thank you and see you again...
Queue Implement by using List

import java.util.Scanner;
class DLink
{
private int data;
public DLink prev;
public DLink next;
public DLink(int data)
{
this.prev=null;
this.data=data;
this.next=null;
}
public DLink(DLink prev,int data,DLink next)
{
this.prev=prev;
this.data=data;
this.next=next;
}
public String Data()
{
return data+"-->";
}
}
class DoubleLinkedList
{
private DLink head;
private int size;
public DoubleLinkedList()
{
head=null;
size=0;
}
public boolean isEmpty()
{
return head==null;
}
public void addFront(int data)
{
if(head==null)
head=new DLink(null,data,null);
else
{
DLink newLink=new DLink(null,data,null);
head.prev=newLink;
newLink.next=head;
head=newLink;
}
size++;
}
public void addLast(int data)
{
if(head==null)
head=new DLink(null,data,null);
else
{
DLink current=head;
while(current.next!=null)
current=current.next;
DLink newLink=new DLink(null,data,null);
current.next=newLink;
newLink.prev=current;

}
size++;
}
public void deleteFront()
{
if(head==null)
return;
else
{
head=head.next;
head.prev=null;
size--;
}
}
public void deleteLast()
{
if(head==null)
return;
if(head.next==null)
{
head=null;
size--;
}
DLink current=head;
while(current.next.next!=null)
current=current.next;
current.next=null;
size--;
}
public void addAny(int data,int pos)
{
if(head==null)
head=new DLink(null,data,null);
DLink current=head;
for(int i=1;i<pos;i++)
current=current.next;
DLink newLink=new DLink(current,data,null);
newLink.next=current.next;
current.next.prev=newLink;
current.next=newLink;
size++;
}
public void deleteAny(int pos)
{
if(head==null)
return;
if(head.next==null)
{
head=null;
size--;
}
DLink current=head;
if(size==2)
{
current.next=null;
size--;
}
else
{
for(int i=1;i<pos;i++)
current.next=current.next.next;
current.next.prev=current;
size--;
}
}
public void reverseTraversal()
{
int i,j;
DLink current=head;
for(i=0;i<size-1;i++)
current=current.next;
for(j=i;j>=0;j--)
{
System.out.print(current.Data());
current=current.prev;
}
System.out.print("null");
}
public void print()
{
if(head==null)
System.out.println("List is empty...");
DLink current=head;
while(current.next!=null)
{
System.out.print(current.Data());
current=current.next;
}
System.out.print(current.Data()+"null");
System.out.println();
}
public static void main(String...args)
{
Scanner sc=new Scanner(System.in);
DoubleLinkedList dll=new DoubleLinkedList();
int info,pos;
while(true)
{
System.out.println("........Menu........");
System.out.println("\n\t\t 1. Add Node At Front \n\t\t 2. Add Node At Rear \n\t\t 3.
Remove Node At Front \n\t\t 4. Remove At Last \n\t\t 5. Add Node At Position \n\t\t 6. Remove
Node At Any pos\n\t\t 7. Display elements in list \n\t\t 8. ReverseTraversal \n\n ");
System.out.println("\n Enter your choice\n");
int choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter data part to a node");
info=sc.nextInt();
dll.addFront(info);
break;
case 2: System.out.println("Enter data part to a node");
info=sc.nextInt();
dll.addLast(info);
break;
case 3: dll.deleteFront();
System.out.println("\n Front node is deleted");
break;
case 4: dll.deleteLast();
System.out.println("\n Last node is deleted");
break;
case 5: System.out.println("Enter the data part to the node");
info=sc.nextInt();
System.out.println("Enter the postion where you insert a node in
list");
pos=sc.nextInt();
dll.addAny(info,pos);
break;
case 6: System.out.println("Enter the postion where you delete a node in
list");
pos=sc.nextInt();
dll.deleteAny(pos);
break;
case 7: dll.print();
break;
case 8: dll.reverseTraversal();
break;
default: System.out.println("You are selection is not there in menu\n");
}
System.out.println("\n \n Do you want to contine....\n Press y or Y for(Yes)|| n or N
for(No)");
char ch=sc.next().charAt(0);
if(ch=='n'||ch=='N')
{
System.out.println("\n\n Thank you see you again..\n\n");
break;
}
}
}
}
Output:
E:\ javac Queue.java 3. Print elements of Queue
4. Display Head
E:\javac QueueImpleByList.java 5. Display Tail

E:\ java QueueImpleByList Enter your choice


.....Menu.... 1
1. EnQueue (Adding the element into Enter the item to be added into the queue
the Queue at rear side -100
2. DeQueue (Deleting a element from Successfully added item in queue
queue at front side)
3. Print elements of Queue Do you want continue...
4. Display Head y
5. Display Tail .....Menu....
1. EnQueue (Adding the element into
the Queue at rear side
Enter your choice 2. DeQueue (Deleting a element from
1 queue at front side)
Enter the item to be added into the queue 3. Print elements of Queue
10 4. Display Head
Do you want continue... 5. Display Tail
y
.....Menu.... Enter your choice
1. EnQueue (Adding the element into 3
the Queue at rear side The elements in the queue are::
2. DeQueue (Deleting a element from 10
queue at front side) 89
3. Print elements of Queue -100
4. Display Head Do you want continue...
5. Display Tail y
.....Menu....
Enter your choice 1. EnQueue (Adding the element into
1 the Queue at rear side
Enter the item to be added into the queue 2. DeQueue (Deleting a element from
89 queue at front side)
Successfully added item in queue 3. Print elements of Queue
4. Display Head
Do you want continue... 5. Display Tail
y
.....Menu....
1. EnQueue (Adding the element into Enter your choice
the Queue at rear side 2
2. DeQueue (Deleting a element from Element is dequeued
queue at front side)
Do you want continue...
Do you want continue... y
y .....Menu....
.....Menu.... 1. EnQueue (Adding the element into
1. EnQueue (Adding the element into the Queue at rear side
the Queue at rear side 2. DeQueue (Deleting a element from
2. DeQueue (Deleting a element from queue at front side)
queue at front side) 3. Print elements of Queue
3. Print elements of Queue 4. Display Head
4. Display Head 5. Display Tail
5. Display Tail
Enter your choice
5
Enter your choice last element in the queue is::
3 -100
The elements in the queue are:: Do you want continue...
89 y
-100 .....Menu....
Do you want continue... 1. EnQueue (Adding the element into
y the Queue at rear side
.....Menu.... 2. DeQueue (Deleting a element from
1. EnQueue (Adding the element into queue at front side)
the Queue at rear side 3. Print elements of Queue
2. DeQueue (Deleting a element from 4. Display Head
queue at front side) 5. Display Tail
3. Print elements of Queue
4. Display Head Enter your choice
5. Display Tail 3
The elements in the queue are::
89
Enter your choice -100
4 Do you want continue...
First element in the queue is:: n
89 Thank you and see you again...
Binary Search Tree

Node class:

public class Node


{
int data;
Node leftChild;
Node rightChild;
Node parent;
public Node()
{
leftChild=rightChild=null;
data=0;
}
public Node(int data)
{
this.data=data;
this.leftChild=null;
this.rightChild=null;
}
public int getData()
{
return data;
}
}
BinarySearchTreeDeletion class:

import java.util.Scanner;
public class BinarySearchTreeDeletion
{
Node root;
public void add(int data)
{
Node nodeToAdd=new Node(data);
if(root==null)
root=nodeToAdd;
else
traverseAndAddNode(root,nodeToAdd);
}
public void traverseAndAddNode(Node node,Node nodeToAdd)
{
if(nodeToAdd.getData()<node.getData())
{
if(node.leftChild==null)
{
nodeToAdd.parent=node;
node.leftChild=nodeToAdd;
}
else
{
traverseAndAddNode(node.leftChild,nodeToAdd);
}
}
else if(nodeToAdd.data>node.data)
{
if(node.rightChild==null)
{
nodeToAdd.parent=node;
node.rightChild=nodeToAdd;
}
else
{
traverseAndAddNode(node.rightChild,nodeToAdd);
}
}
}
public static void preOrderTraversal(Node root)
{
if(root==null)
return;
System.out.println(root.getData()+" ");
preOrderTraversal(root.leftChild);
preOrderTraversal(root.rightChild);
}
public static void inOrderTraversal(Node root)
{
if(root==null)
return;
inOrderTraversal(root.leftChild);
System.out.println(root.getData()+" ");
inOrderTraversal(root.rightChild);

}
public static void postOrderTraversal(Node root)
{
if(root==null)
return;
postOrderTraversal(root.leftChild);
postOrderTraversal(root.rightChild);
System.out.println(root.getData()+" ");
}
public boolean delete(int val)
{
//case 1: node has no childrens
//case 2:node has one child;
//case 3: node has two childrens

Node nodeTobeDeleted=find(val);
if(nodeTobeDeleted!=null)
{
if(nodeTobeDeleted.leftChild==null && nodeTobeDeleted.rightChild==null)
{
deleteCase1(nodeTobeDeleted);
}
else if(nodeTobeDeleted.leftChild!=null && nodeTobeDeleted.rightChild!=null)
{
deleteCase3(nodeTobeDeleted);
}
else if(nodeTobeDeleted.leftChild!=null)
{
deleteCase2(nodeTobeDeleted);
}
else if(nodeTobeDeleted.rightChild!=null)
{
deleteCase2(nodeTobeDeleted);
}
}
return false;
}
public Node find(int val)
{
if(root!=null)
{
return findNode(root,new Node(val));
}
return null;
}
private Node findNode(Node search,Node node)
{
if(search==null)
return null;
if(search.data==node.data)
{
return search;
}
else
{
Node returnNode=findNode(search.leftChild,node);
if(returnNode==null)
{
returnNode=findNode(search.rightChild,node);
}
return returnNode;
}
}
private void deleteCase1(Node nodeTobeDeleted)
{
if(nodeTobeDeleted.parent.leftChild==nodeTobeDeleted)
{
nodeTobeDeleted.parent.leftChild=null;
}
else if(nodeTobeDeleted.parent.rightChild==nodeTobeDeleted)
{
nodeTobeDeleted.parent.rightChild=null;
}
}
private void deleteCase2(Node nodeTobeDeleted)
{
if(nodeTobeDeleted.parent.leftChild==nodeTobeDeleted)
{
if(nodeTobeDeleted.leftChild!=null)
{
nodeTobeDeleted.parent.leftChild=nodeTobeDeleted.leftChild;
}
else if(nodeTobeDeleted.rightChild!=null)
{
nodeTobeDeleted.parent.rightChild=nodeTobeDeleted.rightChild;
}
}
else if(nodeTobeDeleted.parent.rightChild==nodeTobeDeleted)
{
if(nodeTobeDeleted.leftChild!=null)
{
nodeTobeDeleted.parent.rightChild=nodeTobeDeleted.leftChild;
}
else if(nodeTobeDeleted.rightChild!=null)
{
nodeTobeDeleted.parent.rightChild=nodeTobeDeleted.rightChild;
}
}
}
private Node minLeftTraversal(Node node)
{
if(node.leftChild==null)
{
return node;
}
return minLeftTraversal(node.leftChild);
}
private void deleteCase3(Node nodeTobeDeleted)
{
Node minNode=minLeftTraversal(nodeTobeDeleted.rightChild);
deleteCase1(minNode);
minNode.parent=nodeTobeDeleted.parent;
minNode.leftChild=nodeTobeDeleted.leftChild;
minNode.rightChild=nodeTobeDeleted.rightChild;
if(nodeTobeDeleted.parent==null)
{
root=minNode;
}
else
{
if(nodeTobeDeleted.parent.leftChild==nodeTobeDeleted)
{
minNode.parent.leftChild=minNode;
}
else if(nodeTobeDeleted.parent.rightChild==nodeTobeDeleted)
{
minNode.parent.rightChild=minNode;
}
}
}
public static void main(String...args)
{
Scanner s=new Scanner(System.in);
BinarySearchTreeDeletion bst=new BinarySearchTreeDeletion();
bst.add(50);
bst.add(25);
bst.add(75);
bst.add(10);
bst.add(30);
bst.add(60);
bst.add(55);
bst.add(53);
bst.add(85);
bst.add(80);
bst.add(76);
bst.add(1);
bst.add(100);
while(true)
{
System.out.println("\n \t 1. In - Order Traversal \n \t 2. Pre - Order Traversal \n \t 3. Post - Order
Traversal");
int choice;
System.out.println("Enter your choice::");
choice=s.nextInt();
switch(choice)
{
case 1:
System.out.println("In-Order Traversal");
inOrderTraversal(bst.root);
System.out.println();
break;
case 2:
System.out.println("Pre-Order Traversal");
preOrderTraversal(bst.root);
break;

case 3:
System.out.println("post-Order Traversal");
postOrderTraversal(bst.root);
break;
}
System.out.println("Do you want to delete a node enter a node value else press 0");
int no_to_del=s.nextInt();
bst.delete(no_to_del);
if(no_to_del==0)
System.out.println("Node"+no_to_del+"is not there");
else
System.out.println("Node"+no_to_del+"is deleted please select any traversal technique to see the
result");
System.out.println("do you want to continue... \n Press Y||y for 'Yes' OR N || n for 'No'");
char ch=s.next().charAt(0);
if(ch=='N' || ch=='n')
{
System.out.println("Thank you and see you again.....");
break;
}
}
}
}
Output:
E:\ javac Node.java Press Y||y for 'Yes' OR N || n for 'No'
E:\ javac BinarySearchTreeDeletion.java y

E:\ java BinarySearchTreeDeletion 1. In - Order Traversal


2. Pre - Order Traversal
1. In - Order Traversal 3. Post - Order Traversal
2. Pre - Order Traversal Enter your choice::
3. Post - Order Traversal 1
Enter your choice:: In-Order Traversal
1 1
In-Order Traversal 25
1 30
10 50
25 53
30 55
50 60
53 75
55 76
60 80
75 85
76 100
80
85 Do you want to delete a node enter a node
100 value else press 0
0
Do you want to delete a node enter a node Node0is not there
value else press 0 do you want to continue...
10 Press Y||y for 'Yes' OR N || n for 'No'
Node10is deleted please select any traversal n
technique to see the result Thank you and see you again.....
do you want to continue...
Max Heap Tree Implementation
import java.io.*;
class MinHeap
{
private int[] theHeap;
private int capacity;
private int pos;
private int size;
public MaxHeap()
{
pos=1;
capacity=30;
theHeap=new int[capacity];
}
public void insert(int value)
{
if(pos==capacity)
{
return;
}
else
{
theHeap[pos++]=value;
size=size+1;
int child=pos-1;
int parent=child/2;
while(theHeap[parent] <theHeap[child] && parent > 0)
{
int temp=theHeap[parent];
theHeap[parent]=theHeap[child];
theHeap[child]=temp;
child=parent;
parent=child/2;
}
}
}
public void print()
{
for(int i=1;i<=size;i++)
{
System.out.print(" " +theHeap[i]+ " ");
}
}
}
public class MaxHeapImplementation
{
public static void main(String[] args)
{
MaxHeap heap=new MaxHeap();
heap.insert(12);
heap.insert(7);
heap.insert(6);
heap.insert(10);
heap.insert(8);
heap.insert(20);
heap.insert(30);
heap.insert(40);

heap.print();
}
}
Output:
E:\javac MaxHeapImplementation.java

E:\ java MaxHeapImplementation


40 30 20 10 8 6 12 7
Heap Sort Program

import java.util.Scanner;

public class HeapSort{


private static int N;
public static void sort(int arr[]){
heapMethod(arr);
for (int i = N; i > 0; i--){
swap(arr,0, i);
N = N-1;
heap(arr, 0);
}
}
public static void heapMethod(int arr[]){
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
heap(arr, i);
}
public static void heap(int arr[], int i){
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i){
swap(arr, i, max);
heap(arr, max);
}
}
public static void swap(int arr[], int i, int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner( System.in );
int n;
System.out.println("Enter the number of elements to be sorted:");
n = in.nextInt();
int arr[] = new int[ n ];
System.out.println("Enter "+ n +" integer elements");
for (int i = 0; i < n; i++)
arr[i] = in.nextInt();
sort(arr);
System.out.println("After sorting ");
for (int i = 0; i < n; i++)
System.out.println(arr[i]+" ");
System.out.println();
}
}
Output:

E:\ java HeapSort

Enter the number of elements to be sorted:


5
Enter 5 integer elements
12
6
9
8
45
After sorting
6
8
9
12
45
Insertion Sort Program

import java.io.*;
import java.util.Scanner;
class InsertionSort
{
int []a;
int capacity;
int size;
public InsertionSort()
{
capacity=20;
a=new int[capacity];
size=1;
}
public void fillArray(int ele)
{
a[size++]=ele;
}
public void print()
{
for(int i=1;i<size;i++)
System.out.println("\n \t a["+i+"]:"+a[i]+" ");
}
public void sort()
{
for(int i=2;i<size;i++)
{
int key=a[i];
int j=i-1;
while(j>0 && a[j]>key)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=key;
}
}
public static void main(String[] args)
{
InsertionSort is=new InsertionSort();
Scanner s=new Scanner(System.in);
while(true)
{
System.out.println("\n \t ....Menu...");
System.out.println("\n \t 1.Inserting Element \n \t 2. Sort \n \t 3. Display ");
System.out.println("\n \tEnter your choice");
int ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("\n \tEnter the element to be insert");
int ele=s.nextInt();
is.fillArray(ele);
System.out.println("\n \tEnter"+ele+"is inserted");
break;

case 2: is.sort();
System.out.println("\n \tElements are sorted, See the result select third option");
break;

case 3: System.out.println("The elements are:");


is.print();
break;

default: System.out.println("\n \tWrong choice, your choice is not there in menu");


}
System.out.println("\n \tDo you want to continue...");
char say=s.next().charAt(0);
if(say=='N' || say=='n')
{
System.out.println("Process is over...");
break;
}
}
}
}
Output:

E:\java InsertionSort

....Menu...
Enter your choice
1.Inserting Element 1
2. Sort Enter the element to be insert
3. Display 10
Enter your choice
1 Enter10is inserted
Enter the element to be insert
-96 Do you want to continue...
Enter-96is inserted y

Do you want to continue... ....Menu...


y
....Menu... 1.Inserting Element
2. Sort
1.Inserting Element 3. Display
2. Sort
3. Display Enter your choice
2
Enter your choice
1 Elements are sorted, See the result
Enter the element to be insert select third option
-100
Enter-100is inserted Do you want to continue...
y
Do you want to continue... ....Menu...
y
....Menu... 1.Inserting Element
2. Sort
1.Inserting Element 3. Display
2. Sort
3. Display Enter your choice
3
The elements are: a[2]:-96

a[1]:-100 a[3]:10

Merge Sort Program

public class MergesortExample


{
private static int []a;
public static void main(String[] args)
{
a = getArray();
System.out.println("Before sorting the elements are:");
printArray(a);
sort();
System.out.println();
System.out.println("After sorting the elements are:");
printArray(a);
}
public static void sort()
{
int []tempArray = new int[a.length];
mergeSort(tempArray,0,a.length-1);
}
public static void mergeSort(int []tempArray,int lowerIndex,int upperIndex)
{
if(lowerIndex == upperIndex)
{
return;
}
else
{
int mid = (lowerIndex+upperIndex)/2;
mergeSort(tempArray, lowerIndex, mid);
mergeSort(tempArray, mid+1, upperIndex);
merge(tempArray,lowerIndex,mid+1,upperIndex);
}
}
public static void merge(int []tempArray,int lowerIndexCursor,int higerIndex,int
upperIndex)
{
int tempIndex=0;
int lowerIndex = lowerIndexCursor;
int midIndex = higerIndex-1;
int totalItems = upperIndex-lowerIndex+1;
while(lowerIndex <= midIndex && higerIndex <= upperIndex)
{
if(a[lowerIndex] < a[higerIndex])
{
tempArray[tempIndex++] = a[lowerIndex++];
}
else
{
tempArray[tempIndex++] = a[higerIndex++];
}
}
while(lowerIndex <= midIndex)
{
tempArray[tempIndex++] = a[lowerIndex++];
}
while(higerIndex <= upperIndex)
{
tempArray[tempIndex++] = a[higerIndex++];
}
for(int i=0;i<totalItems;i++)
{
a[lowerIndexCursor+i] = tempArray[i];
}
}
public static void printArray(int []array)
{
for(int i : array)
{
System.out.print(i+" ");
}
}
public static int[] getArray()
{
int size=10;
int []array = new int[size];
int item = 0;
for(int i=0;i<size;i++)
{
item = (int)(Math.random()*100);
array[i] = item;
}
return array;
}
}

Output:

E:\java MergesortExample
Before sorting the elements are:
58 95 44 76 60 60 42 90 70 0
After sorting the elements are:
0 42 44 58 60 60 70 76 90 95
Quick Sort Program

import java.util.Scanner;
public class QuickSort
{
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];

while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{

temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

i++;
j--;
}
}

if (low < j)
quickSort(arr, low, j);
if (i < high)
quickSort(arr, i, high);
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
Output:

E:\java QuickSort
Enter number of integer elements
5
Enter 5 integer elements
-10
-20
9
6
3
Elements after sorting
-20 -10 3 6 9
Linear Search

import java.io.*;

import java.util.Scanner;

class LinearSearch

int []theArray;

int size;

int pos;

int capacity;

public LinearSearch()

size=0;

pos=1;

capacity=30;

theArray=new int[capacity];

public void insertElementIntoArray(int ele)

{
theArray[pos++]=ele;

size++;

public void linearSearch(int x)

int status=0;

for(int i=1;i<=size;i++)

if(theArray[i]==x)

System.out.println("Element found at"+i+"th location");

status=1;

break;

if(status==0)

System.out.println("Search is unsuccessfull and element is not found");

public void print()

for(int i=1;i<=size;i++)

System.out.print(" " +theArray[i]+ " ");

}
public static void main(String[] args)

LinearSearch ls=new LinearSearch();

Scanner s=new Scanner(System.in);

while(true)

System.out.println("\n \n \tEnter the element into array");

int ele=s.nextInt();

ls.insertElementIntoArray(ele);

System.out.println("\n \n \tDo you want to enter another element press y or n");

char ch=s.next().charAt(0);

if(ch=='n'||ch=='N')

break;

System.out.println("\n \n \tThe elements in array are");

ls.print();

System.out.println("\n \n \tPlz enter the element to be search");

int s_ele=s.nextInt();

ls.linearSearch(s_ele);

}
Output:

E:\java LinearSearch

Enter the element into array


1
Do you want to enter another element press y or n
y
Enter the element into array
-20
Do you want to enter another element press y or n
y
Enter the element into array
80
Do you want to enter another element press y or n
y
Enter the element into array
90
Do you want to enter another element press y or n
n

The elements in array are


1 -20 80 90

Plz enter the element to be search


10
Search is unsuccessfull and element is not found
Binary Search

import java.io.*;
import java.util.Scanner;
class BinarySearch
{
int []theArray;
int size;
int pos;
int capacity;
public BinarySearch()
{
size=0;
pos=1;
capacity=30;
theArray=new int[capacity];
}
public void insertElementIntoArray(int ele)
{
theArray[pos++]=ele;
size++;
}
public void binarySearch(int x)
{
int low=1,high=size;
while(low<=high)
{
int mid=(low+high)/2;
if(theArray[mid]==x)
{
System.out.println("Element found at" +mid + "position");
break;
}
else if(x<theArray[mid])
{
high=mid-1;
}
else if(x>theArray[mid])
{
low=mid+1;
}
}
if(low>high)
{
System.out.println("Element is not found");
}
}
public void sort()
{
for(int i=1;i<size;i++)
for(int j=i+1;j<=size;j++)
{
if(theArray[i]>theArray[j])
{
int temp=theArray[i];
theArray[i]=theArray[j];
theArray[j]=temp;
}
}
}
public void print()
{
for(int i=1;i<=size;i++)
{
System.out.print(" " +theArray[i]+ " ");
}
}
public static void main(String[] args)
{
BinarySearch bs=new BinarySearch();
Scanner s=new Scanner(System.in);
while(true)
{
System.out.println("\n \n \tEnter the element into array");
int ele=s.nextInt();
bs.insertElementIntoArray(ele);
System.out.println("\n \n \tDo you want to enter another element press y or n");
char ch=s.next().charAt(0);
if(ch=='n'||ch=='N')
{
break;
}
}
System.out.println("\n \n \tThe elements in array are");
bs.print();
System.out.println("\n \n \tPlz enter the element to be search");
int s_ele=s.nextInt();
bs.sort();
bs.binarySearch(s_ele);
}
}
Output:

Successful case:

E:\ java Binary Search


Enter the element into array
1
Do you want to enter another element press y or n
y
Enter the element into array
10
Do you want to enter another element press y or n
n
The elements in array are
1 10
Plz enter the element to be search
1
Element found at1position

Failure Case:
E:\java Binary Search

Enter the element into array


90
Do you want to enter another element press y or n
y
Enter the element into array
120
Do you want to enter another element press y or n
n
The elements in array are
90 120
Plz enter the element to be search
345
Element is not found

You might also like