Professional Documents
Culture Documents
1. Write Java programs that use both recursive and non-recursive functions for
implementing the following searching methods.
AIM: To write a Java program that uses both recursive and non-recursive functions for implementing the following
searching methods i.e Linear search and Binary search.
DESCRIPTION:
Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear
search, we simply traverse the list completely and match each element of the list with the item whose
location is to be found. If the match is found, then the location of the item is returned; otherwise, the
algorithm returns NULL. It is widely used to search an element from the unordered list, i.e., the list in
which items are not sorted. The worst-case time complexity of linear search is O(n). Binary search: Binary
search is the search technique that works efficiently on sorted lists. Hence, to search an element into some
list using the binary search technique, we must ensure that the list is sorted. Binary search follows the
divide and conquer approach in which the list is divided into two halves, and the item is compared with the
middle element of the list. If the match is found then, the location of the middle element is returned.
Otherwise, we search into either of the halves depending upon the result produced through the match.
SOURCE CODE:
class RecursiveBinarySearch{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;}
return -1;}
int n = arr.length;
int x = 10;
if (result == -1)
Else
SOURCE CODE:
class BinarySearch
int mid=(first+last)/2;
if(arr[mid]<key){
first=mid+1;
else if(arr[mid]==key){
break;
else{
mid=(first+last)/2;
if(first>last){
}}
int arr[]={10,20,30,40,50};
int key=30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}}
OUTPUT :
SOURCE CODE:
class RecursiveLinearSearch{
if (r < l)
return -1;
if (arr[l] == x)
return l;
if (arr[r] == x)
int x = 3;
if (index != -1)
else
}}
OUTPUT:
SOURCE CODE:
class LinearSearch{
if (a[i] == val)
return i+1;
return -1;
int a[] = {55, 29, 10, 40, 57, 41, 20, 24, 45}; // given array
System.out.println();
System.out.println();
if (res == -1)
else
} }
OUTPUT:
2. Write Java programs to implement the List ADT using arrays and linked lists.
AIM: To implement the List ADT using arrays and linked list.
DESCRIPTION:
A Linked List stores the elements of the 'List' in separate memory locations and we keep track of the memory
locations as part of the information stored with an element (called a node). – A 'node' in a Linked List contains
the data value as well as the address of the next node.
2.A write a java program to implement the List ADT using Arrays
SOURCE CODE:
import java.util.*;
l.add("Sandy");
l.add("Joe");
l.add("Arya");
l.add("Nik");
OUTPUT:
SOURCE CODE:
import java.util.LinkedList;
class Main
languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
languages.set(3, "Kotlin");
a) StackADT b) QueueADT
AIM:To implement java program of following using an array i.e StackADT and QueueADT.
DESCRIPTION:
A stack is an ordered data structure belonging to the Java Collection Framework. In this collection, the
elements are added and removed from one end only. The end at which the elements are added and
removed is called “Top of the Stack”. As addition and deletion are done only at one end, the first element
added to the stack happens to be the last element removed from the stack. Thus stack is called a LIFO
(Last-in, First-out) data structure. Push: Adds an element to the stack. As a result, the value of the top is
incremented.
Pop: An element is removed from the stack. After the pop operation, the value of the top is
decremented.
Peek: This operation is used to look up or search for an element. The value of the top is not modified.
Queue ADT: Queue is also an abstract data type or a linear data structure, just like stack data structure, in
which the first element is inserted from one end called the REAR(also called tail), and the removal of
existing element takes place from the other end called as FRONT(also called head). This makes queue as
FIFO(First in First Out) data structure, which means that element inserted first will be removed first.
Queue can be implemented by using arrays as well as link list
(a) StackADT:
SOURCECODE:
import java.util.*;
class Stack
int[] stack_arry = new int[maxsize]; //define array that will hold stack elements
Stack()
top = -1;
boolean isEmpty()
{ //isEmpty () method
if(top == maxsize-1){
return false; }
else{
top++;
stack_arry[top]=val;
return true;
} }
boolean pop ()
{ //pop () method
if (top == -1) {
return false;
else {
return true;
} }
} } }
stck.push(10);
stck.push(30);
stck.push(40);
stck.display();
stck.pop();
stck.pop();
stck.display();
}}
OUTPUT:
(b) QueueADT:
SOURCECODE:
class Queue {
Queue(int size){
front = rear = 0;
capacity = size;
if (capacity == rear) {
System.out.printf("\nQueue is full\n");
return;
else {
queue[rear] = item;
rear++;
return;
if (front == rear) {
System.out.printf("\nQueue is empty\n");
return;
else {
queue[rear] = 0;
rear--;
return;
int i;
if (front == rear) {
return;
return;
if (front == rear) {
System.out.printf("Queue is Empty\n");
return;
return;
}}
System.out.println("Initial Queue:");
q.queueDisplay();
q.queueEnqueue(10);
q.queueEnqueue(30);
q.queueEnqueue(50);
q.queueEnqueue(70);
q.queueDisplay();
q.queueFront();
q.queueEnqueue(90);
q.queueDisplay();
q.queueDequeue();
q.queueDequeue();
q.queueFront();
} }
OUTPUT:
4. Write a java program that reads an infix expression, converts the expression to postfix
form and then evaluates the postfix expression (use stack ADT).
AIM: To implement the java program that reads an infix expression, coverts the expression to postfix form
and then evaluate the postfix expression.
DESCRIPTION:
To convert infix expression to postfix expression, we will use the stack data structure. By
scanning the infix expression from left to right, when we will get any operand, simply add them to
the postfix form, and for the operator and parenthesis, add them in the stack maintaining the
precedence of them.
SOURCE CODE:
import java.io.*;
class Stack {
int top=-1;
void push(char c) {
try {
a[++top]= c;
catch(StringIndexOutOfBoundsException e) {
System.exit(0);
} }
char pop() {
return a[top--];
boolean isEmpty() {
return (top==-1)?true:false;
char peek() {
return a[top];
} }
String infix;
infix = keyboard.readLine();
char symbol;
for(int i=0;i<infix.length();++i) {
symbol = infix.charAt(i);
if (Character.isLetter(symbol))
else if (symbol=='(')
//push ( {
operators.push(symbol);
else if (symbol==')')
else
operators.push(symbol);
} }
while (!operators.isEmpty())
return postfix;
if (x == '+' || x == '-')
return 1;
return 2;
return 0;
} }
OUTPUT:
5. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT (b) Queue ADT
AIM: To implement the Stack ADT and queue ADT using singly linked list.
DESCRIPTION:
Linked List is an Abstract Data Type (ADT) that holds a collection of Nodes, the nodes can be accessed in
a sequential way. When the Nodes are connected with only the next pointer the list is called Singly Linke
List. A linked list is a series of connected nodes, where each node is a data structure.
stack is a linked list that allows insertion / removal only from its tail, and. queue is a linked list that allows
insertion only at its tail and removal only from its head.
a)Stack ADT:
SOURCE CODE:
import java.util.*;
class Node{
public Node(){
link = null;
data = 0;
data = d;
link = n;
link = n;
data = d;
return link;
return data;
}}
class linkedStack{
public linkedStack() {
top = null;
size = 0;}
return size;
if (top == null)
top = nptr;
else {
nptr.setLink(top);
top = nptr;
size++ ;
if (isEmpty() )
top = ptr.getLink();
size-- ;
return ptr.getData();
if (isEmpty() )
return top.getData();
System.out.print("\nStack = ");
if (size == 0) {
System.out.print("Empty\n");
return ;
System.out.print(ptr.getData()+" ");
ptr = ptr.getLink();
System.out.println();
}}
char ch;
do {
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. peek");
System.out.println("5. size");
switch (choice) {
case 1 :
ls.push( scan.nextInt() );
break;
case 2 :
try{
catch (Exception e) {
break;
case 3 :
try{
break;
case 4 :
case 5 :
break;
case 6 :
System.out.println("Stack = ");
ls.display();
break;
default :
break;
ls.display();
ch = scan.next().charAt(0);
}}
OUTPUT:
SOURCE CODE:
// Java program for linked-list implementation of queue
class QNode
{ int key;
QNode next ;
this.key = key;
this.next = null ;
}}
class Queue
public Queue ()
if (this.rear == null)
return;
this.rear.next = temp;
this.rear = temp;
if (this.front == null)
return;
this.front = this.front.next;
if (this.front == null)
this.rear = null;
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
OUTPUT:
6)Write Java programs to implement the deque (double ended queue) ADT using
(a) Array (b) Doubly linked list.
AIM: To implement the deque (double ended queue) ADT using Array and Doubly linked list.
DESCRIPTION:
A deque or double-ended queue is an ordered group of items that functions similarly to a queue. It has two ends, a
front and a back, and the items in the collection remain in place,while the Deque can mimic many of the properties
of stacks and queues, it doesn't require the LIFO and FIFO orderings that those data structures enforce. It is up to
you to use the addition and removal operations consistently.
SOURCE CODE:(a)
import java.util.*;
class Book
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity)
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
} }
//Creating Books
set.add(b1);
set.add(b2);
set.add(b3);
for(Book b:set)
} } }
OUTPUT:
int i;
Node next;
Node prev;
Node(int i){
}}
public LinkedListDeque(){
this.head = null;
this.tail = null;
if(isEmpty()){
tail = newNode;
}else{
head.prev = newNode;
newNode.next = head;
head = newNode;
if(isEmpty()){
head = newNode;
}else{
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
if(head == null){
if(head.next == null){
tail = null;
}else{
head.next.prev = null;
head = head.next;
return first;
if(tail == null){
if(head.next == null){
head = null;
}else{
tail.prev.next = null;
tail = tail.prev;
return last;
if(isEmpty()){
return head.i;
if(isEmpty()){
return tail.i;
while(current != null){
current.displayData();
current = current.next;
System.out.println("");
while(current != null){
current.displayData();
current = current.prev;
System.out.println("");
deque.insertFirst(2);
deque.insertFirst(1);
deque.insertLast(3);
deque.insertLast(4);
deque.displayForward();
deque.displayForward();
}}
Output:
DESCRIPTION:
Priority Queue is an abstract data type that is similar to a queue, and every element has some
priority value associated with it. The priority of the elements in a priority queue determines the order
in which elements are served (i.e., the order in which they are removed).
SOURCE CODE:
import java.util.* ;
class Priorityqueue
int data;
int priority;
Node next;
temp.data = d;
temp.priority = p;
temp.next = null;
return temp; }
return (head).data;
(head) = (head).next;
return head;
if ((head).priority < p) {
temp.next = head;
(head) = temp; }
else {
start.next.priority > p) {
start = start.next;
return head;
pq =push(pq, 5, 2);
pq =push(pq, 6, 3);
while (isEmpty(pq)==0){
}}}
OUTPUT:
(8) Write Java programs that use recursive and non-recursive functions to traverse the
given binary tree in (a) Preorder (b) In order and (c) Post order.
AIM:To implement Java programs that use recursive and non-recursive functions to traverse the given binary tree in
(a) Preorder (b) In order and (c) Post order.
DESCRIPTION:
1. .
SOURCE CODE:
class Node {
value = element;
} }
class Tree {
if (node == null)
return;
traversePreorder(node.left);
if (node == null)
return;
traverseInorder(node.left);
traverseInorder(node.right);
if (node == null)
return;
traversePostorder(node.left);
traversePostorder(node.right);
System.out.println();
pt.traversePreorder();
System.out.println("\n");
pt.traverseInorder();
System.out.println("\n");
pt.traversePostorder();
System.out.println();
} }
OUTPUT:
(9) Write a Java program that displays node values in a level order traversal (Traverse the
tree one level at a time, starting at the root node) for a binary tree.
AIM: To implement the display node values in a level order traversal (Traverse the tree one level at a time,
starting at the root node) for a binary tree using java program.
DESCRIPTION:
Traversal is a common operation performed on data structures. It is the process in which each and every
element present in a data structure is "visited" (or accessed) at least once. This may be done to display
all of the elements or to perform an operation on all of the elements.
SOURCE CODE:
class Node
int data;
data = item;
}}
Node root;
public BinaryTree() {
root = null;
void printLevelOrder() {
int h = height(root);
printCurrentLevel(root, i);
if (root == null)
return 0;
else
else
}}
if (root == null)
return;
if (level == 1)
tree.printLevelOrder();
}}
OUTPUT:
10. Write a Java program that uses recursive functions. (a) To create a binary search tree.
(b) To count the number of leaf nodes. (c) To copy the above binary search tree.
AIM: To implement the uses recursive functions. (a) To create a binary search tree. (b) To count the number of leaf
nodes. (c) To copy the above binary search tree using a java program.
DESCRIPTION:
Recursive Function is a function that repeats or uses its own previous term to calculate subsequent terms
and thus forms a sequence of terms. Usually, we learn about this function based on the
arithmetic-geometric sequence, which has terms with a common difference between them.
SOURCE CODE:
class Node {
int item;
}}
class Mains {
Node root;
Mains() {
root = null;
if(node == null){
return 0;
return 1;
else{
} }
}}
OUTPUT:
11. Write Java programs for the implementation of bfs and dfs for a given graph.
AIM: To implement the java program of bfs and dfs for a given graph.
DESCRIPTION:
BFS can be used to find a single source shortest path in an unweighted graph because, in BFS, we reach a
vertex with a minimum number of edges from a source vertex. In DFS, we might traverse through more
edges to reach a destination vertex from a source.
11b)write a java program for the implementation of DPS for a given graph
SOURCE CODE:
import java.io.*;
import java.util.*;
class Graph {
private int V;
public Graph(int v) {
V = v;
}}
adj[v].add(w);
nodes[vertex] = true;
int a = 0;
a = adj[vertex].get(i);
if (!nodes[a]) {
DFSUtil(a, nodes);
DFSUtil(v, already);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 0);
g.addEdge(1, 3);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 3);
g.addEdge(5, 3);
g.DFS(0);
}}
OUTPUT:
11.B write java program for the implementation of BFS for a given graph
import java.io.*;
import java.util.*;
private int V;
Graph1(int v) {
V = v;
adj[v].add(w);
visited[s]=true;
queue.add(s);
s = queue.poll();
System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}}}}
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2);
}}
OUTPUT:
12. Write Java programs for implementing the following sorting methods:
(a) Bubble sort (b) Selection sort (c) Insertion sort (d) Radix sort
AIM: To implement the java program for the following sorting methods
a) Bubble sort b) Selection sort
DESCRIPTION:
Bubble sort is a basic algorithm for arranging a string of numbers or other elements in the correct order.
The method works by examining each set of adjacent elements in the string, from left to right, switching
their positions if they are out of order.
Selection sort is an effective and efficient sort algorithm based on comparison operations. It adds one
element in each iteration. You need to select the smallest element in the array and move it to the beginning
of the array by swapping with the front element.
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a
time by comparisons. It is much less efficient on large lists than more advanced algorithms such as
quicksort, heapsort, or merge sort.
Radix sort is an integer sorting algorithm that sorts data with integer keys by grouping the keys by
individual digits that share the same significant position and value (place value). Radix sort uses
counting sort as a subroutine to sort an array of numbers.
(a)Bubble sort:
SOURCE CODE:
int n = arr.length;
int temp = 0;
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
} } } }
System.out.println();
}}}
OUTPUT:
SOURCE CODE:
int index = i;
arr[index] = arr[i];
arr[i] = smallerNumber;
}}
for(int i:arr1){
System.out.print(i+" ");
System.out.println();
for(int i:arr1){
System.out.print(i+" ");
} }}
OUTPUT:
(C) InsertionSort():
SOURCE CODE:
int n = array.length;
int i = j-1;
i--;
array[i+1] = key;
}}
for(int i:arr1){
System.out.print(i+" ");
System.out.println();
for(int i:arr1){
System.out.print(i+" ");
} } }
OUTPUT:
d:Insertion Sort():
SOURCE CODE:
max = a[i];
a[i] = output[i];
countingSort(a, n, place);
int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2};
int n = a.length;
r1.printArray(a,n);
r1.radixsort(a, n);
r1.printArray(a, n);
} }
OUTPUT:
13. Write a Java program for implementing KMP pattern matching algorithm.
AIM: To implement KMP pattern matching algorithm using java program.
DESCRIPTION:
KMP algorithm is used to find a "Pattern" in a "Text". This algorithm compares character by character from
left to right. But whenever a mismatch occurs, it uses a preprocessed table called "Prefix Table" to skip
characters comparison while matching
SOURCE CODE:
class KMP{
return;
if (text == null
return;
{ j = next[j];
} }
}}
}}}
}}
OUTPUT: