Sem-Iv Recordmodifing
Sem-Iv Recordmodifing
Program - 1
1. Write a program to implement the linked list operations
Singly Linked Lists are a type of data structure. It is a type of list. In a singly
linked list each node in the list stores the contents of the node and a pointer or
reference to the next node in the list. It does not store any pointer or reference to
the previous node. It is called a singly linked list because each node only has a single
link to another node. To store a single linked list, you only need to store a reference
or pointer to the first node in that list. The last node has a pointer to nothingness to
indicate that it is the last node.
Here is the pictorial view of inserting an element in the middle of a singly linked list:
Here is the pictorial view of deleting an element in the middle of a singly linked list:
Add at the Start : Add a node the beginning of the linked list. Its O(1).
Add at the End : Add a node at the end of the linked list. its O(n) since to add a node at
the end you need to go till the end of the array.
Delete at the Start : Delete a node from beginning of the linked list. Its O(1).
Delete at the End : Delete a node from the end of the linked list. its O(n) since to delete
a node at the end you need to go till the end of the array.
Get Size: returns the size of the linked list.
Get Element at Index : Return the element at specific index, if index is greater than the
size then return –1. its O(n) in worst case.
Add Element at Specific Index : Add element at specific index. If index is greater than
size then print “INVALID POSITION”. Worst case its O(n)
Display(): Prints the entire linked list. O(n).
Program:
public class LinkListImplementation {
public static void main(String[] args) throws java.lang.Exception {
LinkedListT a = new LinkedListT();
a.addAtBegin(5);
a.addAtBegin(15);
a.addAtEnd(20);
a.addAtEnd(21);
a.deleteAtBegin();
a.deleteAtEnd();
a.addAtIndex(10, 2);
a.addAtEnd(15);
a.display();
System.out.println("\n Size of the list is: " + a.size);
System.out.println(" Element at 2nd position : " + a.elementAt(2));
Output:
The two node links allow traversal of the list in either direction. While adding or
removing a node in a doubly-linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more
efficient, because there is no need to keep track of the previous node during traversal or
no need to traverse the list to find the previous node, so that its link can be modified.
Here is the pictorial view of inserting an element in the middle of a doubly linked list:
Here is the pictorial view of deleting an element in the middle of a doubly linked list:
Algorithm:
Output:
Alogrithm:
Add at the Start : Add a node the beginning of the linked list. Its O(1).
Add at the End : Add a node at the end of the linked list. its O(n) since to add a node at
the end you need to go till the end of the array.
Delete at the Start : Delete a node from beginning of the linked list. Its O(1).
Delete at the End : Delete a node from the end of the linked list. its O(n) since to delete
a node at the end you need to go till the end of the array.
Get Size: returns the size of the linked list.
Get Element at Index : Return the element at specific index, if index is greater than the
size then return –1. its O(n) in worst case.
Add Element at Specific Index : Add element at specific index. If index is greater than
size then print “INVALID POSITION”. Worst case its O(n)
Display(): Prints the entire linked list. O(n).
Program:
public class CircularLinkedList {
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}
Output:
Program - 2
ACTS DEGREE COLLEGE 16
DATA STRUCTURES USING JAVA SEMESTER-IV
In a Stack, keep track of maximum value in it. It might be the top element in the
stack but once it is poped out, the maximum value should be from the rest of the ele-
ments in the stack.
Approach:
Create another another Stack(call it as track) which will keep track of maximum in
the given Stack(call it as main).
When you insert an element in the main stack for the first time (means it is
empty), insert it in the track Stack as well.
Now onwards when you insert a new element(say it is x) in the main Stack,
peek() the element from the track Stack ( say it is ‘a’). Compare x and a and which
ever is greater, insert it into track Stack.
When you pop the element from the main stack, pop from the track Stack as well
So to get to know the maximum element in the main Stack, peek the element in
the track Stack. ..
/**
* @author Nagesh Chauhan
*/
public class StackDemo {
private static final int capacity = 3;
int arr[] = new int[capacity];
int top = -1;
stackDemo.pop();
stackDemo.push(23);
stackDemo.push(2);
stackDemo.push(73);
ACTS DEGREE COLLEGE 18
DATA STRUCTURES USING JAVA SEMESTER-IV
stackDemo.push(21);
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
}
Output:
Program – 3
ACTS DEGREE COLLEGE 19
DATA STRUCTURES USING JAVA SEMESTER-IV
Program:
import java.util.*;
class arrayQueue
{
protected int Queue[] ;
protected int front, rear, size, len;
public arrayQueue(int n)
{
size = n;
len = 0;
Queue = new int[size];
front = -1;
rear = -1;
}
public boolean isEmpty()
{
return front == -1;
}
public boolean isFull()
{
return front==0 && rear == size -1 ;
}
public int getSize()
{
return len ;
}
public int peek()
{
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
return Queue[front];
}
public void insert(int i)
{
if (rear == -1)
{
front = 0;
rear = 0;
Queue[rear] = i;
}
ACTS DEGREE COLLEGE 20
DATA STRUCTURES USING JAVA SEMESTER-IV
else if (rear + 1 >= size)
throw new IndexOutOfBoundsException("Overflow Exception");
else if ( rear + 1 < size)
Queue[++rear] = i;
len++ ;
}
public int remove()
{
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
else
{
len-- ;
int ele = Queue[front];
if ( front == rear)
{
front = -1;
rear = -1;
}
else
front++;
return ele;
}
}
public void display()
{
System.out.print("\nQueue = ");
if (len == 0)
{
System.out.print("Empty\n");
return ;
}
for (int i = front; i <= rear; i++)
System.out.print(Queue[i]+" ");
System.out.println();
}
}
public class QueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Output:
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
4
Empty status = true
Queue = Empty
Queue Operations
1. insert
ACTS DEGREE COLLEGE 23
DATA STRUCTURES USING JAVA SEMESTER-IV
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
24
Queue = 24
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
6
Queue = 246
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
16
Queue = 24616
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
19
Queue = 2461619
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
32
Queue = 246161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
14
Error : Overflow Exception
ACTS DEGREE COLLEGE 25
DATA STRUCTURES USING JAVA SEMESTER-IV
Queue = 246161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
5
Full status = true
Queue = 246161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
3
Peek Element = 24
Queue = 246161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
ACTS DEGREE COLLEGE 26
DATA STRUCTURES USING JAVA SEMESTER-IV
Removed Element = 24
Queue = 6161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 6
Queue = 161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
6
Size = 3
Queue = 161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
ACTS DEGREE COLLEGE 27
DATA STRUCTURES USING JAVA SEMESTER-IV
3
Peek Element = 16
Queue = 161932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 16
Queue = 1932
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 19
Queue = 32
y
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
ACTS DEGREE COLLEGE 28
DATA STRUCTURES USING JAVA SEMESTER-IV
2
Removed Element = 32
Queue = Empty
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Error : Underflow Exception
Queue = Empty
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
4
Empty status = true
Queue = Empty
This is a Java Program to implement a Singly Linked List. A linked list is a data
structure consisting of a group of nodes which together represent a sequence. Under the
simplest form, each node is composed of a data and a reference (in other words, a link)
to the next node in the sequence. This structure allows for efficient insertion or removal
ACTS DEGREE COLLEGE 29
DATA STRUCTURES USING JAVA SEMESTER-IV
of elements from any position in the sequence. In a singly linked list each node has only
one link which points to the next node in the list.
Here is the source code of the Java program to implement Singly Linked List. The Java
program is successfully compiled and run on a Windows system. The program output is
also shown below.
Program:
import java.util.Scanner;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedList
{
protected Node start;
protected Node end ;
ACTS DEGREE COLLEGE 30
DATA STRUCTURES USING JAVA SEMESTER-IV
public int size ;
public linkedList()
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty()
{
return start == null;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
public void insertAtEnd(int val)
{
Node nptr = new Node(val,null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
}
Output:
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5
1. insert at begining
ACTS DEGREE COLLEGE 35
DATA STRUCTURES USING JAVA SEMESTER-IV
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
7
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
4
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
9
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
3
Enter position
3
1. insert at begining
2. insert at end
3. insert at position
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 7
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
4
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
y
Singly Linked List Operations
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true
Program - 5
5. Write a program to implement the queue operations using a singly linked list.
This is a Java Program to implement a Doubly Linked List. A linked list is a data
structure consisting of a group of nodes which together represent a sequence. Under the
simplest form, each node is composed of a data and a reference (in other words, a link)
to the next node in the sequence. This structure allows for efficient insertion or removal
of elements from any position in the sequence. In a doubly linked list each node has two
links one pointing to the next node in the list and one pointing to the previous node in
the list.
Here is the source code of the Java program to implement Doubly Linked List.
The Java program is successfully compiled and run on a Windows system. The program
output is also shown below.
ACTS DEGREE COLLEGE 41
DATA STRUCTURES USING JAVA SEMESTER-IV
Program:
import java.util.Scanner;
class Node
{
protected int data;
protected Node next, prev;
public Node()
{
next = null;
prev = null;
data = 0;
}
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
public void setLinkNext(Node n)
{
next = n;
}
public void setLinkPrev(Node p)
{
prev = p;
}
public Node getLinkNext()
{
return next;
}
public Node getLinkPrev()
{
return prev;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
ACTS DEGREE COLLEGE 42
DATA STRUCTURES USING JAVA SEMESTER-IV
return data;
}
}
class linkedList
{
protected Node start;
protected Node end ;
public int size;
public linkedList()
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty()
{
return start == null;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
public void display()
{
System.out.print("\nDoubly Linked List = ");
/* Class DoublyLinkedList */
public class DoublyLinkedList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList();
System.out.println("Doubly Linked List Test\n");
char ch;
do
{
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
Output:
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
ACTS DEGREE COLLEGE 48
DATA STRUCTURES USING JAVA SEMESTER-IV
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
6
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
7
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
3
Enter position
3
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
4
Enter position
4
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 5
1. insert at begining
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
Doubly Linked List = empty
Do you want to continue(Type y or n)
Program – 6
Program:
/*
ACTS DEGREE COLLEGE 54
DATA STRUCTURES USING JAVA SEMESTER-IV
* Java Program to Evaluate an Expression using Stacks
*/
import java.util.*;
OutPut:
Program – 7
7. Write program to implement double ended queue using a doubly linked list
Program:
/*
* Java Program to Implement Double Ended Queue
*/
ACTS DEGREE COLLEGE 57
DATA STRUCTURES USING JAVA SEMESTER-IV
import java.util.*;
/* Class Node */
class Node
{
protected int data;
protected Node link;
/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}
/* Class Dequeue */
class Dequeue
{
/* Constructor */
public Dequeue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Clear dequeue */
public void clear()
{
front = null;
rear = null;
size = 0;
}
/* Function to insert an element at begining */
public void insertAtFront(int val)
{
Node nptr = new Node(val, null);
size++ ;
if (front == null)
{
front = nptr;
rear = front;
}
else
{
nptr.setLink(front);
front = nptr;
}
}
/* Function to insert an element at end */
public void insertAtRear(int val)
{
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to remove rear element from the queue */
public int removeAtRear()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception");
int ele = rear.getData();
Node s = front;
Node t = front;
while (s != rear)
{
t = s;
s = s.getLink();
}
rear = t;
rear.setLink(null);
size --;
return ele;
}
/* Class DoubleEndedQueueTest */
public class DoubleEndedQueueTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class Dequeue */
Dequeue dq = new Dequeue();
/* Perform Dequeue Operations */
System.out.println("Dequeue Test\n");
char ch;
do
{
Output:
Dequeue Test
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
Dequeue = 5
Dequeue = 85
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
2
Enter integer element to insert
3
Dequeue = 853
Do you want to continue(Type y or n)
ACTS DEGREE COLLEGE 64
DATA STRUCTURES USING JAVA SEMESTER-IV
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
2
Enter integer element to insert
45
Dequeue = 85345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
1
Enter integer element to insert
28
Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
5
Peek Element = 28
ACTS DEGREE COLLEGE 65
DATA STRUCTURES USING JAVA SEMESTER-IV
Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
6
Peek Element = 45
Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
7
Size = 5
Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
3
ACTS DEGREE COLLEGE 66
DATA STRUCTURES USING JAVA SEMESTER-IV
Removed Element = 28
Dequeue = 85345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
4
Removed Element = 45
Dequeue = 853
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
3
Removed Element = 8
Dequeue = 53
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
ACTS DEGREE COLLEGE 67
DATA STRUCTURES USING JAVA SEMESTER-IV
7
Size = 2
Dequeue = 53
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
9
Dequeue Cleared
Dequeue = Empty
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
8
Empty status = true
Dequeue = Empty
N
ACTS DEGREE COLLEGE 68
DATA STRUCTURES USING JAVA SEMESTER-IV
Program - 8
8. Write a program to search an item in a given list using linear search and binary
search.
(a) Linear Search:
Java program for linear search: Linear search is very simple, To check if an
element is present in the given list we compare search element with every element in
the list. If the number is found then success occurs otherwise the list doesn't contain the
element we are searching.
Program:
import java.util.Scanner;
Output:
To search any element present inside the array in Java Programming using linear
search technique, you have to use only one for loop to check whether the entered number is
found in the list or not as shown in the following program.
Program:
import java.util.Scanner;
first = 0;
last = n-1;
middle = (first+last)/2;
Program - 9
This is a Java Program to implement Quick Sort Algorithm. This program is to sort
a list of numbers.
Here is the source code of the Java program to implement Quick Sort Algorithm. The
Java program is successfully compiled and run on a Windows system. The program
output is also shown below.
Program:
import java.util.Scanner;
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++)
Out put:
Program - 10
This is a Java Program to implement Merge Sort on an integer array. Merge sort
is an O(n log n) comparison-based sorting algorithm. Most implementations produce a
stable sort, which means that the implementation preserves the input order of equal
elements in the sorted output. Merge sort is a divide and conquer algorithm that was
invented by John von Neumann in 1945.
Conceptually, a merge sort works as follows :
i) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element
is considered sorted).
ii) Repeatedly merge sublists to produce new sublists until there is only 1 sublist
remaining. This will be the sorted list.
Program:
/*
* Java Program to Implement Merge Sort
*/
import java.util.Scanner;
/* Class MergeSort */
public class MergeSort
{
/* Merge Sort function */
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
Output:
Program – 11
11. Write a program on binary search tree operatios (insertion, deletion and traversals)
ACTS DEGREE COLLEGE 78
DATA STRUCTURES USING JAVA SEMESTER-IV
This is a Java Program to implement Binary Search Tree. A binary search tree
(BST), sometimes also called an ordered or sorted binary tree, is a node-based binary
tree data structure which has the following properties:
i) The left subtree of a node contains only nodes with keys less than the node’s
key.
ii) The right subtree of a node contains only nodes with keys greater than the
node’s key.
iii) The left and right subtree must each also be a binary search tree.
iv) There must be no duplicate nodes.
Generally, the information represented by each node is a record rather than a
single data element. However, for sequencing purposes, nodes are compared
according to their keys rather than any part of their associated records. The
major advantage of binary search trees over other data structures is that the
related sorting algorithms and search algorithms such as in-order traversal can be
very efficient. Binary search trees are a fundamental data structure used to
construct more abstract data structures such as sets, multisets, and associative
arrays.
Program:
import java.util.Scanner;
class BSTNode
{
BSTNode left, right;
int data;
public BSTNode()
{
left = null;
right = null;
data = 0;
}
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
public void setLeft(BSTNode n)
{
left = n;
ACTS DEGREE COLLEGE 79
DATA STRUCTURES USING JAVA SEMESTER-IV
}
public void setRight(BSTNode n)
{
right = n;
}
public BSTNode getLeft()
{
return left;
}
public BSTNode getRight()
{
return right;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
return data;
}
}
class BST
{
private BSTNode root;
public BST()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
public void insert(int data)
{
root = insert(root, data);
}
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
Output:
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
8
Post order : 8
Pre order : 8
In order : 8
Do you want to continue(Type y or n)
y
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
5
Post order : 58
Pre order : 85
In order : 58
Do you want to continue(Type y or n)
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
3
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
7
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
10
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
15
1. insert
2. delete
ACTS DEGREE COLLEGE 87
DATA STRUCTURES USING JAVA SEMESTER-IV
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
2
1. insert
2. delete
3. search
4. count nodes
5. check empty
4
Nodes = 7
1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
24
Search result : false
1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
7
Search result : true
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
2
2 deleted from the tree
1. insert
2. delete
3. search
4. count nodes
ACTS DEGREE COLLEGE 89
DATA STRUCTURES USING JAVA SEMESTER-IV
5. check empty
2
Enter integer element to delete
8
8 deleted from the tree
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
10
10 deleted from the tree
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
5
5 deleted from the tree
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
15
15 deleted from the tree
Post order : 37
Pre order : 73
In order : 37
Do you want to continue(Type y or n)
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
3
3 deleted from the tree
Post order : 7
Pre order : 7
In order : 7
Do you want to continue(Type y or n)
1. insert
2. delete
3. search
ACTS DEGREE COLLEGE 91
DATA STRUCTURES USING JAVA SEMESTER-IV
4. count nodes
5. check empty
2
Enter integer element to delete
77
Sorry 77 is not present
Post order : 7
Pre order : 7
In order : 7
Do you want to continue(Type y or n)
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
7
7 deleted from the tree
Post order :
Pre order :
In order :
Do you want to continue(Type y or n)
1. insert
2. delete
3. search
4. count nodes
5. check empty
5
Empty status = true
Post order :
Pre order :
In order :
Do you want to continue(Type y or n)
Program - 12
This Java program,performs the DFS traversal on the given graph represented by
a adjacency matrix.the DFS traversal makes use of an stack.
Here is the source code of the Java program to perform the dfs traversal. The Java
program is successfully compiled and run on a Linux system. The program output is also
shown below.
Program:
ACTS DEGREE COLLEGE 93
DATA STRUCTURES USING JAVA SEMESTER-IV
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS
{
private Stack<Integer> stack;
public DFS()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + "\t");
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{
Output: