1st Sem Aadvance Algorithm Practicals File
1st Sem Aadvance Algorithm Practicals File
Practical File
On
Master of Technology
In
Computer Science & Engineering
Faculty Signature
(Ms. Swapna Singh)
PROGRAM: 1
OBJECTIVE: Write Java programs that use both recursive and non-recursive
functions for implementing the following searching methods: a) Linear search
b) Binary search.
Output
9 is found at index: 5
Binary search Search Program Using Non Recursion
class GFG {
int binarySearch(int arr[], int x)
{
int l = 0, int 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;
}
public static void main(String args[])
{
GFG ob = new GFG();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "
+ result);
}
}
Output:
Element found at index 3
import java.util.*;
class GFG {
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l && l <= arr.length - 1) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
public static void main(String args[])
{
GFG ob = new GFG();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index "
+ result);
}
}
Output
Element is present at index 3
PROGRAM 2
OBJECTIVE: Write a Java program to implement all the functions of a dictionary
(ADT) using Hashing.
import java.io.*;
import java.util.*;
class AddElementsToHashtable {
public static void main(String args[])
{
Hashtable<Integer, String> ht1 = new Hashtable<>();
Output
Mappings of ht1: {Lucky=Delhi, Davis=USA, Andrew=France}
PROGRAM 3
OBJECTIVE: Write Java programs for implementing the following sorting
methods: a) Bubble sort b) Insertion sort c) Quick sort d) Merge sort e) Heap
sort f) Radix sort g) Binary tree sort.
a) Bubble Sort
public class BubbleSortExample {
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 arr[] ={3,60,35,2,45,320,5};
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:
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
b) Insertion Sort
class InsertionSort {
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
printArray(arr);
}
}
Output:
5 6 11 12 13
c) Quick Sort
import java.io.*;
class GFG{
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int partition(int[] arr, int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
Output
Sorted array:
1 5 7 8 9 10
d) Merge sort
class MergeSort
{
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r)
{
if (l < r) {
// Find the middle point
int m =l+ (r-l)/2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length - 1);
System.out.println("\nSorted array");
printArray(arr);
}
}
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
e) Heap Sort
public class HeapSort {
public void sort(int arr[])
{
int n = arr.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
Output
Sorted array is
5 6 7 11 12 13
f) Radix Sort
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
Output
6 12 25 161 415 573
g) Binary Tree Sort
class GFG
{
class Node
{
int key;
Node left, right;
}
public static void main(String[] args)
{
GFG tree = new GFG();
int arr[] = {5, 4, 7, 2, 11};
tree.treeins(arr);
tree.inorderRec(tree.root);
}
}
Output:
2 4 5 7 11
PROGRAM 4
OBJECTIVE: Write Java programs that use recursive and non-recursive
functions to traverse the given binary tree in a) Preorder b) Inorder c)
Postorder.
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class BinaryTree {
Node root;
BinaryTree() { root = null; }
"bottom-up" postorder traversal. */
void printPostorder(Node node)
{
if (node == null)
return;
printPostorder(node.left);
printPostorder(node.right);
System.out.print(node.key + " ");
}
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.key + " ");
printInorder(node.right);
}
void printPreorder(Node node)
{
if (node == null)
return;
System.out.print(node.key + " ");
printPreorder(node.left);
printPreorder(node.right);
}
void printPostorder() { printPostorder(root); }
void printInorder() { printInorder(root); }
void printPreorder() { printPreorder(root); }
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println(
"Preorder traversal of binary tree is ");
tree.printPreorder();
System.out.println(
tree.printInorder();
System.out.println(
tree.printPostorder();
}
}
Output:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231
PROGRAM 5
OBJECTIVE: Write Java programs for the implementation of bfs and dfs for a
given graph.
Implementation of BFS
import java.io.*;
import java.util.*;
class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v,int w)
{
adj[v].add(w);
}
void BFS(int s)
{
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
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);
}
}
}
}
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal "+
"(starting from vertex 2)");
g.BFS(2);
}
}
Output:
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
Implementation of DFS
import java.io.*;
import java.util.*;
class Graph {
private int V; // No. of vertices
private LinkedList<Integer> adj[];
@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
}
void DFSUtil(int v, boolean visited[])
{
visited[v] = true;
System.out.print(v + " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
void DFS(int v)
{
boolean visited[] = new boolean[V];
DFSUtil(v, visited);
}
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");
g.DFS(2);
}
}
Output:
Following is Depth First Traversal (starting from vertex 2)
2 0 1 3
PROGRAM 6
OBJECTIVE: Write a Java program to implement Dijkstra’s algorithm for
Single source shortest path problem.
import java.util.*;
import java.io.*;
import java.lang.*;
public class DijkstraExample
{
static final int totalVertex = 9;
int minimumDistance(int distance[], Boolean spSet[])
{
int m = Integer.MAX_VALUE, m_index = -1;
for (int vx = 0; vx < totalVertex; vx++)
{
if (spSet[vx] == false && distance[vx] <= m)
{
m = distance[vx];
m_index = vx;
}
}
return m_index;
}
void printSolution(int distance[], int n)
{
System.out.println("The shortest Distance from source 0th node to all other nodes are: ");
for (int j = 0; j < n; j++)
System.out.println("To " + j + " the shortest distance is: " + distance[j]);
}
void dijkstra(int graph[][], int s)
{
int distance[] = new int[totalVertex]; // The output array distance[i] holds the shortest dista
nce from source s to j
Boolean spSet[] = new Boolean[totalVertex];
for (int j = 0; j < totalVertex; j++)
{
distance[j] = Integer.MAX_VALUE;
spSet[j] = false;
}
distance[s] = 0;
for (int cnt = 0; cnt < totalVertex - 1; cnt++)
{
int ux = minimumDistance(distance, spSet);
spSet[ux] = true;
for (int vx = 0; vx < totalVertex; vx++)
if (!spSet[vx] && graph[ux][vx] != -
1 && distance[ux] != Integer.MAX_VALUE && distance[ux] + graph[ux][vx] < distance[vx])
{
distance[vx] = distance[ux] + graph[ux][vx];
}
}
printSolution(distance, totalVertex);
}
public static void main(String argvs[])
{
int grph[][] = new int[][] { { -1, 3, -1, -1, -1, -1, -1, 7, -1 },
{ 3, -1, 7, -1, -1, -1, -1, 10, 4 },
{ -1, 7, -1, 6, -1, 2, -1, -1, 1 },
{ -1, -1, 6, -1, 8, 13, -1, -1, 3 },
{ -1, -1, -1, 8, -1, 9, -1, -1, -1 },
{ -1, -1, 2, 13, 9, -1, 4, -1, 5 },
{ -1, -1, -1, -1, -1, 4, -1, 2, 5 },
{ 7, 10, -1, -1, -1, -1, 2, -1, 6 },
{ -1, 4, 1, 3, -1, 5, 5, 6, -1 } };
DijkstraExample obj = new DijkstraExample();
obj.dijkstra(grph, 0);
}
}
Output:
The shortest Distance from source 0th node to all other nodes are:
To 0 the shortest distance is: 0
To 1 the shortest distance is: 3
To 2 the shortest distance is: 8
To 3 the shortest distance is: 10
To 4 the shortest distance is: 18
To 5 the shortest distance is: 10
To 6 the shortest distance is: 9
To 7 the shortest distance is: 7
To 8 the shortest distance is: 7
PROGRAM 7
OBJECTIVE: Write a Java program that implements Kruskal’s algorithm to
generate minimum cost spanning tree
import Java.util.*;
class KruskalAlgorithm {
class Edge implements Comparable<Edge> {
int source, destination, weight;
public int compareTo(Edge edgeToCompare) {
return this.weight - edgeToCompare.weight;
}
};
class Subset {
int parent, value;
};
int vertices, edges;
Edge edgeArray[];
KruskalAlgorithm(int vertices, int edges) {
this.vertices = vertices;
this.edges = edges;
edgeArray = new Edge[this.edges];
for (int i = 0; i < edges; ++i)
edgeArray[i] = new Edge(); //create edge for all te edges given by the user
}
void applyKruskal() {
Edge finalResult[] = new Edge[vertices];
int newEdge = 0;
int index = 0;
for (index = 0; index < vertices; ++index)
finalResult[index] = new Edge();
Arrays.sort(edgeArray);
Subset subsetArray[] = new Subset[vertices];
for (index = 0; index < vertices; ++index)
subsetArray[index] = new Subset();
for (int vertex = 0; vertex < vertices; ++vertex) {
subsetArray[vertex].parent = vertex;
subsetArray[vertex].value = 0;
}
index = 0;
while (newEdge < vertices - 1) {
Edge nextEdge = new Edge();
nextEdge = edgeArray[index++];
int nextSource = findSetOfElement(subsetArray, nextEdge.source);
int nextDestination = findSetOfElement(subsetArray, nextEdge.destination);
if (nextSource != nextDestination) {
finalResult[newEdge++] = nextEdge;
performUnion(subsetArray, nextSource, nextDestination);
}
}
for (index = 0; index < newEdge; ++index)
System.out.println(finalResult[index].source + " - " + finalResult[index].destination + "
: " + finalResult[index].weight);
}
int findSetOfElement(Subset subsetArray[], int i) {
if (subsetArray[i].parent != i)
subsetArray[i].parent = findSetOfElement(subsetArray, subsetArray[i].parent);
return subsetArray[i].parent;
}
}
public void display() {
display(root);
}
private void display(Node x) {
assert (x == null);
for (int i = 0; i < x.n; i++) {
System.out.print(x.key[i] + " ");
}
if (!x.leaf) {
for (int i = 0; i < x.n + 1; i++) {
display(x.child[i]);
}
}
}
public static void main(String[] args) {
BTree b = new BTree(3);
b.insert(8);
b.insert(9);
b.insert(10);
b.insert(11);
b.insert(15);
b.insert(20);
b.insert(17);
b.display();
}
}
OUTPUT
PROGRAM 9
OBJECTIVE: Write a Java program that implements KMP algorithm for
pattern matching.
class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
int lps[] = new int[M];
int j = 0; // index for pat[]
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
System.out.println("Found pattern "
+ "at index " + (i - j));
j = lps[j - 1];
}
else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if (len != 0) {
len = lps[len - 1];
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
public static void main(String args[])
{
String txt = "ABABDABACDABABCABAB";
String pat = "ABABCABAB";
new KMP_String_Matching().KMPSearch(pat, txt);
}
}
Output:
Found pattern at index 10