Algorithms Manual (1)
Algorithms Manual (1)
Students should enter his/her name, system number and in time while entering into the
laboratory.
Students should submit his/her observation note before they start working in the system.
After completing the experiments, verification of the program should be obtained from
the concern staff in-charges.
Students should arrange the chair and the system in a proper manner, and they should
enter the out time in the lab register.
COURSE OBJECTIVES:
To build software development skills using java programming for real-world applications.
To understand and apply the concepts of classes, packages, interfaces, inheritance,
exception handling and file processing.
To develop applications using generic programming and event handling
LIST OF EXPERIMENTS:
1. Implement Linear Search. Determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.
2. Implement recursive Binary Search. Determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.
3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ],
char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.
4. Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the elements. Repeat the experiment for different
values of n, the number of elements in the list to be sorted and plot a graph of the time
taken versus n.
5. Develop a program to implement graph traversal using Breadth First Search
7. From a given vertex in a weighted connected graph, develop a program to find the
shortest paths to other vertices using Dijkstra’s algorithm.
8. Find the minimum cost spanning tree of a given undirected graph using Prim’s
algorithm.
10. Compute the transitive closure of a given directed graph using Warshall's algorithm.
11. Develop a program to find out the maximum and minimum numbers in a given list of
n numbers using the divide and conquer technique.
12. Implement Merge sort and Quick sort methods to sort an array of elements and
determine the time required to sort. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n.
State Space Search Algorithms
14. Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm
and determine the error in the approximation.
15. Implement randomized algorithms for finding the kth smallest number. The
programs can be implemented in C/C++/JAVA/ Python.
Lab Requirements:
LIST OF EXPERIMENTS:
1. Implement Linear Search. Determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.
2. Implement recursive Binary Search. Determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.
3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ],
char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.
4. Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the elements. Repeat the experiment for different
values of n, the number of elements in the list to be sorted and plot a graph of the time
taken versus n.
7. From a given vertex in a weighted connected graph, develop a program to find the
shortest paths to other vertices using Dijkstra’s algorithm.
8. Find the minimum cost spanning tree of a given undirected graph using Prim’s
algorithm.
10. Compute the transitive closure of a given directed graph using Warshall's algorithm.
11. Develop a program to find out the maximum and minimum numbers in a given list of
n numbers using the divide and conquer technique.
12. Implement Merge sort and Quick sort methods to sort an array of elements and
determine the time required to sort. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n.
State Space Search Algorithms
14. Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm
anddetermine the error in the approximation.
15. Implement randomized algorithms for finding the kth smallest number. The programs
can be implemented in C/C++/JAVA/ Python.
CO COURSE OUTCOME K
At the end of the course student will be able to LEVEL
CO1 Analyze the efficiency of algorithms using various frameworks K3
CO2 Apply graph algorithms to solve problems and analyze their efficiency. K3
Make use of algorithm design techniques like divide and conquer, dynamic
CO3 programming and greedy techniques to solve problems K3
CO4 Use the state space tree method for solving problems. K6
CO5 Solve problems using approximation algorithms and randomized algorithms K3
CS3401- ALGORITHM LABORATORY
Table of Contents
AIM :
ALGORITHM :
1. Start by defining a function called linear_search_array that takes in two parameters: an array of
elements and the element to be searched.
2. Loop through each element in the array using a for loop.
3. Check if the current element is equal to the element to be searched. If true, return the index of the
element.
4. If the element is not found in the array, return -1.
PROGRAM :
import java.util.Scanner;
class Example2
{
public static void main(String args[])
{
int i,len, key, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter Array length:");
len = input.nextInt();
array = new int[len];
System.out.println("Enter " + len + " elements");
for (i = 0; i < len; i++)
{
array[i] = input.nextInt();
}
System.out.println("Enter the search key value:");
key = input.nextInt();
for (i = 0; i < len; i++)
{
if (array[i]== key)
{
System.out.println(key+" is present at location "+(i+1));
break;
}
}
if (i == len)
System.out.println(key + " doesn't exist in array.");
}
}
OTUPUT :
Enter a Elements :
5 4 3 2 1 0 11 7 9
1 is found at location 5
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.Scanner;
class RecursionExample3
{
int recursionSearch(int arr[], int start, int last, int x)
{
if (last < start)
return -1;
if (arr[start] == x)
return start;
return recursionSearch(arr, start+1, last, x);
}
public static void main(String args[])
{
RecursionExample3 ref=new RecursionExample3();
int i,len, key, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter Array length:");
len = input.nextInt();
array = new int[len];
System.out.println("Enter " + len + " elements");
for (i = 0; i < len; i++)
{
array[i] = input.nextInt();
}
System.out.println("Enter the search key value:");
key = input.nextInt()
int index=ref.recursionSearch(array,0,len-1,key);
if (index!=-1)
{
System.out.println(key+" is found at location "+(index+1));
}
else
{
System.out.println(key + " doesn't exist in array.");
}
}
}
OUTPUT :
Enter a Elements :
5 4 3 2 11 0 1 7 9
11 is present at location 5
RESULT :
AIM :
ALGORITHM :
1. Start by defining a function called binary_search_array that takes in two parameters: an array of
elements and the element to be searched.
2. Initialize two variables, low and high, to the first and last indices of the array respectively
3. Loop through the array while low is less than or equal to high.
4. Calculate the middle index as (low + high) // 2.
5. Check if the element at the middle index is equal to the element to be searched. If true, return
the middle index.
6. If the element at the middle index is greater than the element to be searched, update high to be
one less than the middle index
7. If the element at the middle index is less than the element to be searched, update low to be one
more than the middle index.
8. If the element is not found in the array, return -1.
PROGRAM :
import java.util.Scanner;
class Main {
int binarySearch(int array[], int element, int low, int high)
{while (low <= high) {
int mid = low + (high - low) / 2;
// if element to be searched is the mid element
if (array[mid] == element)
return mid;
// if element is less than mid element
// search only the left side of mid
if (array[mid] < element)
low = mid + 1;
// if element is greater than mid element
// search only the right side of mid
else
high = mid - 1;
}
return -1;
}
public static void main(String args[]) {
// create an object of Main class
Main obj = new Main();
// create a sorted array
int[] array = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
// get input from user for element to be searched
Scanner input = new Scanner(System.in);
System.out.println("Enter element to be searched:");
// element to be searched
int element = input.nextInt();
input.close();
// call the binary search method
// pass arguments: array, element, index of first and last element
int result = obj.binarySearch(array, element, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}
OUTPUT :
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.Scanner;
public class BinarySearchRecursive
{ public static void main(String[] args)
{
Scanner commandReader = new Scanner(System.in);
System.out.println("Welcome to Java Program to perform
binary search on int array");
System.out.println("Enter total number of elements : ");
int length = commandReader.nextInt();
int[] input = new int[length];
System.out.printf("Enter %d integers %n", length);
for (int i = 0; i < length; i++) {
input[i] = commandReader.nextInt();
}
System.outprintln("Please enter number to be searchedin array (sorted order)");int key =
commandReader.nextInt();
if (index == -1) {
System.out.printf("Sorry, %d is not found in array %n", key);
} else {
System.out.printf("%d is found in array at index %d %n", key, index);
}
commandReader.close();
}
public static int recursiveBinarySearch(int[] input, int key)
{return binarySearch(input, 0, input.length - 1, key);
}
private static int binarySearch(int[] array, int start, int end, int target)
{int middle = (start + end) / 2;
if (end < start)
{return -1;
}
if (target == array[middle])
{return middle;
} else if (target < array[middle]) {
return binarySearch(array, start, middle - 1, target);
} else {
return binarySearch(array, middle + 1, end, target);
}
}
}
OUTPUT :
Enter 5 integer
12367
RESULT :
AIM :
ALGORITHM :
1. Start by defining a function called naive_algorithm that takes in two parameters: an array of
elements and the element to be searched.
2. Loop through each element in the array.
3. Check if the current element is equal to the element to be searched. If true, return the index of the
current element.
4. If the element is not found in the array, return -1.
PROGRAM :
int j
/* For current index i, check for pattern
match */
for (j = 0; j < M; j++)
if (txt.charAt(i + j) != pat.charAt(j))
break;
RESULT :
AIM :
ALGORITHM :
1. Start by defining a function called insertion_sort that takes in an array of elements as a parameter.
2. Loop through each element in the array, starting from the second element.
3. Compare the current element with the previous element. If the current element is smaller, then
swap them.
4. Continue comparing and swapping the current element with the previous element until the current
element is in its correct position.
5. Repeat steps 2-4 for all elements in the array.
PROGRAM :
import java.util.*;
public class Main {
public static void main(String[] args) {
//declare an array and print the original contents
int[] numArray = {10,6,15,4,1,45};
System.out.println("Original Array:" + Arrays.toString(numArray));
//apply insertion sort algorithm on the array
for(int k=1; k<numArray.length-1; k++) {
int temp = numArray[k];
int j= k-1;
while(j>=0 && temp <= numArray[j])
{numArray[j+1] = numArray[j];
j = j-1;
}
numArray[j+1] = temp;
}
//print the sorted array
System.out.println("Sorted Array:" + Arrays.toString(numArray));
}
}
OUTPUT :
RESULT :
AIM :
ALGORITHM :
1. Start by defining a function called heap_sort that takes in an array of elements as a parameter.
2. Convert the array into a max heap by using a heapify function. This involves comparing each parent node
with its children and swapping them if necessary to ensure that the parent node is greater than both of its
children.
3. Once the array has been converted into a max heap, swap the root node (which is the largest element) with
the last element in the array.
4. Remove the last element from the array (which is now the largest element) and add it to a sorted list.
5. Repeat steps 2-4 for the remaining elements in the array, until all elements have been added to the sorted
list.
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 :
3 66 70 53 22 90 100
After sorting 3
22
53
66
70
90
100
RESULT :
AIM :
To write a java program for Implementation of graph traversal using Breadth First Search
ALGORITHM :
PROGRAM :
import java.io.*;
import java.util.*;
public class BFSTraversal
{
private int node;
private LinkedList<Integer> adj[];
private Queue<Integer> que;
BFSTraversal(int v)
{
node = v;
adj = new LinkedList[node];
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>();
}
que = new LinkedList<Integer>();
}
void insertEdge(int v,int w)
{adj[v].add(w);
}
void BFS(int n)
{
boolean nodes[] = new boolean[node];
int a = 0;
nodes[n]=true;
que.add(n);
while (que.size() != 0)
{
n = que.poll();
System.out.print(n+" ");
for (int i = 0; i < adj[n].size(); i++)
{
a = adj[n].get(i);
if (!nodes[a])
{
nodes[a] = true;
que.add(a);
}
}
}
}
public static void main(String args[])
{
BFSTraversal graph = new BFSTraversal(6);
graph.insertEdge(0, 1);
graph.insertEdge(0, 3);
graph.insertEdge(0, 4);
graph.insertEdge(4, 5);
graph.insertEdge(3, 5);
graph.insertEdge(1, 2);
graph.insertEdge(1, 0);
graph.insertEdge(2, 1);
graph.insertEdge(4, 1);
graph.insertEdge(3, 1);
graph.insertEdge(5, 4);
graph.insertEdge(5, 3);
System.out.println("Breadth First Traversal for the graph is:");
graph.BFS(0);
}
OTUPUT :
013425
RESULT :
AIM :
To write a java program for Implementation of graph traversal using Depth First Search
ALGORITHM :
PROGRAM :
import java.util.*;
class DFSTraversal {
private LinkedList<Integer> adj[];
private boolean visited[];
DFSTraversal(int V)
{
adj = new LinkedList[V];
visited = new boolean[V];
for (int i = 0; i < V; i++)
adj[i] = new LinkedList<Integer>();
}
void insertEdge(int src, int dest)
{adj[src].add(dest);
}
void DFS(int vertex)
{ visited[vertex] = true;
System.out.print(vertex + " ");
Iterator<Integer> it = adj[vertex].listIterator();
while (it.hasNext()) {
int n = it.next();
if (!visited[n])
DFS(n);
}
}
public static void main(String args[])
{ DFSTraversal graph = new
DFSTraversal(8);graph.insertEdge(0, 1);
graph.insertEdge(0, 2);
graph.insertEdge(0, 3);
graph.insertEdge(1, 3);
graph.insertEdge(2, 4);
graph.insertEdge(3, 5);
graph.insertEdge(3, 6);
graph.insertEdge(4, 7);
graph.insertEdge(4, 5);
graph.insertEdge(5, 2);
System.out.println("Depth First Traversal for the graph is:");
graph.DFS(0);
}
}
OUTPUT :
01352476
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.*;
import java.io.*;
import java.lang.*;
public class DijkstraExample
{
static final int totalVertex = 9;
int minimumDistance(int distance[], Boolean spSet[]) 12.
{
int m = Integer.MAX_VALUE, m_index = -1;
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
RESULT :
AIM :
ALGORITHM :
1. Create a set of unvisited nodes, a set of visited nodes, and a dictionary of minimum distances.
2. Choose a starting node and add it to the visited set.
3. For each neighbor of the starting node, add it to the unvisited set and set its minimum distance
to the weight of the edge between it and the starting node.
4. While there are unvisited nodes, do the following:
a. Find the node in the unvisited set with the smallest minimum distance in the dictionary of
minimum distances.
b. Add this node to the visited set and remove it from the unvisited set.
c. For each neighbor of the current node that is still in the unvisited set, do the following:
i. If the weight of the edge between the current node and the neighbor is smaller than the
current minimum distance for the neighbor in the dictionary of minimum distances,
update the minimum distance in the dictionary.
d. Repeat steps a-c until all nodes have been visited.
5. Return the set of visited nodes and the dictionary of minimum distances.
PROGRAM :
import java.lang.*;
import java.util.*;
import java.io.*;
class MinimumSpanningTreeExample {
private static final int countOfVertices = 9;
int findMinKeyVertex(int keys[], Boolean setOfMST[])
{
int minimum_index = -1;
int minimum_value = Integer.MAX_VALUE;
for (int vertex = 0; vertex < countOfVertices; vertex++)
if (setOfMST[vertex] == false && keys[vertex] < minimum_value)
{
minimum_value = keys[vertex];
minimum_index = vertex;
}
return minimum_index;
}
void showMinimumSpanningTree(int mstArray[], int graphArray[][])
{
System.out.println("Edge \t\t Weight");
for (int j = 1; j < countOfVertices; j++)
System.out.println(mstArray[j] + " <- > " + j + "\t \t" + graphArray[j][mstArray[j]]);
}
void designMST(int graphArray[][])
{
int mstArray[] = new int[countOfVertices];
int keys[] = new int[countOfVertices];
Edge Weight
0 <- > 1 4
1 <- > 2 8
2 <- > 3 7
3 <- > 4 9
2 <- > 5 4
5 <- > 6 2
6 <- > 7 1
2 <- > 8 2
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.ArrayList;
import java.util.List;
class Main
{
private static void printPath(int[][] path, int v, int u, List<Integer> route)
{
if (path[v][u] == v)
{return; }
printPath(path, v, path[v][u], route);
route.add(path[v][u]);
}
private static void printSolution(int[][] path, int n)
{
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
if (u != v && path[v][u] != -1)
{
List<Integer> route = new ArrayList<>();
route.add(v);
printPath(path, v, u, route);
route.add(u);
System.out.printf("The shortest path from %d —> %d is %s\n",
v, u, route);
}
}
}
}
public static void floydWarshall(int[][] adjMatrix)
{
if (adjMatrix ==null || adjMatrix.length == 0) { return;
}
int n = adjMatrix.length;
int[][] cost = new int[n][n];
int[][] path = new int[n][n];
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
cost[v][u] = adjMatrix[v][u];
if (v == u) {
path[v][u] = 0;
}
else if (cost[v][u] != Integer.MAX_VALUE)
{path[v][u] = v;
}
else
{ path[v][u] = -
1;
}
}
}
for (int k = 0; k < n; k++)
{
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
if (cost[v][k] != Integer.MAX_VALUE
&& cost[k][u] != Integer.MAX_VALUE
&& (cost[v][k] + cost[k][u] < cost[v][u]))
{
cost[v][u] = cost[v][k] + cost[k][u];
path[v][u] = path[k][u];
}
}
if (cost[v][v] < 0)
{
System.out.println("Negative-weight cycle found!!");
return;
}
}
}
printSolution(path, n); }
public static void main(String[] args)
{
int I = Integer.MAX_VALUE;
int[][] adjMatrix = new int[][]
{
{ 0, I, -2, I },
{ 4, 0, 3, I },
{ I, I, 0, 2 },
{ I, -1, I, 0 }
};
floydWarshall(adjMatrix);
}
}
OUTPUT :
RESULT ;
AIM :
ALGORITHM :
PROGRAM :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Edge{
int source, dest;
public Edge(int source, int dest)
{
this.source = source;
this.dest = dest;
}
}
class Graph
{
List<List<Integer>> adjList = null;
Graph(List<Edge> edges, int n)
{
adjList = new ArrayList<>();
for (int i = 0; i < n; i++)
{ adjList.add(new
ArrayList<>());
}
for (Edge edge: edges)
{
int src = edge.source;
int dest = edge.dest; adjList.get(src).add(dest);
}
}
}
class Main
{
public static void DFS(Graph graph, byte[][] C, int root, int descendant)
{
for (int child: graph.adjList.get(descendant))
{
if (C[root][child] == 0)
{
C[root][child] = 1;
DFS(graph, C, root, child);
}
}
}
public static void main(String[] args)
{
List<Edge> edges = Arrays.asList(
new Edge(0, 2), new Edge(1, 0), new Edge(3, 1)
);
Graph graph = new Graph(edges, n);
byte C[][] = new byte[n][n];
for (int v = 0; v < n; v++)
{
C[v][v] = 1;
DFS(graph, C, v, v);
System.out.println(Arrays.toString(C[v]));
}
}
}
OUTPUT :
[1, 0, 1, 0]
[1, 1, 1, 0]
[0, 0, 1, 0]
[1, 1, 1, 1]
RESULT :
AIM :
ALGORITHM :
1. Define a base case for the problem that can be solved directly without recursion.
2. Divide the problem into smaller subproblems that can be solved recursively.
3. Conquer each subproblem by solving it recursively.
4. Combine the solutions of the subproblems to solve the original problem.
5.Stop the process
PROGRAM :
class Pair
{int max;
int min;
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args)
{int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
long startTime = System.nanoTime();
quickSort(arr, 0, arr.length - 1);
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000000; // Convert to milliseconds
System.out.println("Sorted array: " + Arrays.toString(arr));
System.out.println("Time taken: " + duration + " milliseconds");
}
public static void quickSort(int[] arr, int low, int high)
{if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
private static int partition(int[] arr, int low, int high)
{int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot)
{i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j)
{int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
OUTPUT :
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.Arrays;
public class MergeSortExample
{ public static void main(String[] args)
{
int[] arr = { 5, 1, 9, 3, 7, 4, 6, 2, 8 };
System.out.println("Unsorted Array: " + Arrays.toString(arr));
long startTime = System.nanoTime();
mergeSort(arr, 0, arr.length - 1);
long endTime = System.nanoTime();
System.out.println("Sorted Array: " + Arrays.toString(arr));
long timeRequired = endTime - startTime;
System.out.println("Time Required: " + timeRequired + " nanoseconds");
}
public static void merge(int[] arr, int start, int mid, int end)
{int n1 = mid - start + 1;
int n2 = end - mid; int[]
left = new int[n1];
int[] right = new int[n2];
for (int i = 0; i < n1; ++i)
{left[i] = arr[start + i];
}
for (int j = 0; j < n2; ++j)
{right[j] = arr[mid + 1 +
j];
}
int i = 0, j = 0;
int k = start;
while (i < n1 && j < n2)
{if (left[i] <= right[j])
{arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}
while (i < n1)
{arr[k] = left[i];
i++;
k++;
}
while (j < n2)
{ arr[k] =
right[j];j++;
k++;
}
}
}
OUTPUT :
RESULT :
AIM :
ALGORITHM :
PROGRAM :
public NQueens(int N)
{this.N = N;
this.queenPositions = new int[N];
}
- Q - -
- - - Q
Q - - -
- - Q -
RESULT :
AIM :
ALGORITHM :
1. Travelling salesman problem takes a graph G {V, E} as an input and declare another graph as
the output (say G’) which will record the path the salesman is going to take from one node to
another.
2. The algorithm begins by sorting all the edges in the input graph G from the least distance to the
largest distance.
3. The first edge selected is the edge with least distance, and one of the two vertices (say A and B)
being the origin node (say A).
4. Then among the adjacent edges of the node other than the origin node (B), find the least cost
edge and add it onto the output graph.
5. Continue the process with further nodes making sure there are no cycles in the output graph
and the path reaches back to the origin node A.
6. However, if the origin is mentioned in the given problem, then the solution must always start
from that node only. Let us look at some example problems to understand this better
PROGRAM :
import java.util.*;
public class TSP {
int N;
int[][] distances;
int[] tour;
int tourLength;
public TSP(int N, int[][] distances)
{this.N = N;
this.distances = distances;
this.tour = new int[N];
}
public void solve() {
int[] cities = new int[N];
for (int i = 0; i < N; i++) {
cities[i] = i;
}
permute(cities, 0);
System.out.println("Optimal tour: " + Arrays.toString(tour));
System.out.println("Optimal tour length: " + tourLength);
int[] approxTour = new int[N];
boolean[] visited = new boolean[N];
Random rand = new Random();
int start = rand.nextInt(N);
approxTour[0] = start;
visited[start] = true;
for (int i = 1; i < N; i++) {
int prev = approxTour[i-1];
int next = -1;
int minDist = Integer.MAX_VALUE;
for (int j = 0; j < N; j++) {
if (!visited[j] && distances[prev][j] < minDist)
{minDist = distances[prev][j];
next = j;
}
}
approxTour[i] = next;
visited[next] = true;
}
int approxLength = tourLength(approxTour);
System.out.println("Approximate tour: " + Arrays.toString(approxTour));
System.out.println("Approximate tour length: " + approxLength);
double error = ((double) approxLength - tourLength) / tourLength * 100;
System.out.println("Error in approximation: " + error + "%");
}
private void permute(int[] cities, int start)
{if (start == N) {
int length = tourLength(cities);
if (tourLength == 0 || length < tourLength)
{tourLength = length;
System.arraycopy(cities, 0, tour, 0, N);
}
} else {
for (int i = start; i < N; i++)
{swap(cities, start, i);
permute(cities, start + 1);
swap(cities, start, i);
}
}
}
private int tourLength(int[] cities)
{int length = 0;
for (int i = 0; i < N; i++) {
length += distances[cities[i]][cities[(i+1) % N]];
}
return length;
}
RESULT :
AIM :
ALGORITHM :
PROGRAM :
import java.util.*;
public class RandomizedSelect {
public static int randomizedSelect(int[] arr, int k)
{int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (left <= right) {
int pivotIndex = rand.nextInt(right - left + 1) + left;
int newPivotIndex = partition(arr, left, right, pivotIndex);
int rank = newPivotIndex - left + 1;
if (rank == k) {
return arr[newPivotIndex];
} else if (k < rank) {
right = newPivotIndex - 1;
} else {
k -= rank;
left = newPivotIndex + 1;
}
}
return -1;
}
private static int partition(int[] arr, int left, int right, int pivotIndex)
{int pivotValue = arr[pivotIndex];
swap(arr, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++)
{if (arr[i] < pivotValue)
{ swap(arr, i,
storeIndex);
storeIndex++;
}
}
swap(arr, storeIndex, right);
return storeIndex;
}
RESULT :