[Go to site: main page, start]

0% found this document useful (0 votes)
11 views6 pages

Java Algorithm Lab Code Examples

The document contains Java implementations of various algorithms including sorting (Merge Sort), searching (Binary Search), greedy (Activity Selection), dynamic programming (0/1 Knapsack), divide and conquer (Maximum Subarray), backtracking (N-Queens), graph (Dijkstra's Algorithm), tree (DFS), and string (KMP Pattern Matching). Each algorithm is presented with its respective class and methods, demonstrating how to solve specific problems efficiently. These codes serve as practical examples for learning algorithm design and implementation in Java.

Uploaded by

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

Java Algorithm Lab Code Examples

The document contains Java implementations of various algorithms including sorting (Merge Sort), searching (Binary Search), greedy (Activity Selection), dynamic programming (0/1 Knapsack), divide and conquer (Maximum Subarray), backtracking (N-Queens), graph (Dijkstra's Algorithm), tree (DFS), and string (KMP Pattern Matching). Each algorithm is presented with its respective class and methods, demonstrating how to solve specific problems efficiently. These codes serve as practical examples for learning algorithm design and implementation in Java.

Uploaded by

alaminsheak276
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Algorithm Lab Codes in Java

1. Sorting Algorithms - 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, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) arr[k++] = L[i++];
else arr[k++] = R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}
void sort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l)/2;
sort(arr, l, m);
sort(arr, m+1, r);
merge(arr, l, m, r);
}
}
}

2. Searching Algorithms - Binary Search

class BinarySearch {
int binarySearch(int arr[], int x) {
int l = 0, r = [Link] - 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;
}
}

3. Greedy Algorithms - Activity Selection

import [Link].*;
class ActivitySelection {
Algorithm Lab Codes in Java

static class Activity {


int start, end;
Activity(int start, int end) { [Link] = start; [Link] = end; }
}
static void printMaxActivities(Activity arr[], int n) {
[Link](arr, [Link](a -> [Link]));
int i = 0;
[Link]("(" + arr[i].start + ", " + arr[i].end + ")");
for (int j = 1; j < n; j++) {
if (arr[j].start >= arr[i].end) {
[Link]("(" + arr[j].start + ", " + arr[j].end + ")");
i = j;
}
}
}
}

4. Dynamic Programming - 0/1 Knapsack Problem

class Knapsack {
int knapSack(int W, int wt[], int val[], int n) {
int dp[][] = new int[n+1][W+1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (wt[i-1] <= w)
dp[i][w] = [Link](val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w]);
else
dp[i][w] = dp[i-1][w];
}
}
return dp[n][W];
}
}

5. Divide and Conquer - Maximum Subarray (DC version)

class MaxSubArray {
int maxCrossingSum(int arr[], int l, int m, int h) {
int sum = 0, left_sum = Integer.MIN_VALUE;
for (int i = m; i >= l; i--) {
sum += arr[i];
if (sum > left_sum) left_sum = sum;
}
sum = 0;
int right_sum = Integer.MIN_VALUE;
for (int i = m + 1; i <= h; i++) {
sum += arr[i];
Algorithm Lab Codes in Java

if (sum > right_sum) right_sum = sum;


}
return left_sum + right_sum;
}
int maxSubArraySum(int arr[], int l, int h) {
if (l == h) return arr[l];
int m = (l + h)/2;
return [Link]([Link](maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h)),
maxCrossingSum(arr, l, m, h));
}
}

6. Backtracking - N-Queens Problem

class NQueens {
final int N = 8;
boolean isSafe(int board[][], int row, int col) {
for (int i = 0; i < col; i++)
if (board[row][i] == 1) return false;
for (int i=row, j=col; i>=0 && j>=0; i--, j--)
if (board[i][j] == 1) return false;
for (int i=row, j=col; j>=0 && i<N; i++, j--)
if (board[i][j] == 1) return false;
return true;
}
boolean solveNQUtil(int board[][], int col) {
if (col >= N) return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1)) return true;
board[i][col] = 0;
}
}
return false;
}
void solveNQ() {
int board[][] = new int[N][N];
if (!solveNQUtil(board, 0)) {
[Link]("Solution does not exist");
return;
}
printSolution(board);
}
void printSolution(int board[][]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
[Link](" " + board[i][j] + " ");
Algorithm Lab Codes in Java

[Link]();
}
}
}

7. Graph Algorithms - Dijkstra's Algorithm

import [Link].*;
class Dijkstra {
int V = 9;
int minDistance(int dist[], boolean sptSet[]) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (!sptSet[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
return min_index;
}
void dijkstra(int graph[][], int src) {
int dist[] = new int[V];
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != 0 &&
dist[u] != Integer.MAX_VALUE &&
dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
void printSolution(int dist[]) {
[Link]("Vertex Distance from Source");
for (int i = 0; i < V; i++)
[Link](i + " " + dist[i]);
}
}

8. Tree Algorithms - DFS on Tree

import [Link].*;
class DFS {
Algorithm Lab Codes in Java

static void dfs(int v, boolean visited[], List<List<Integer>> adj) {


visited[v] = true;
[Link](v + " ");
for (int u : [Link](v)) {
if (!visited[u])
dfs(u, visited, adj);
}
}
public static void main(String[] args) {
int V = 5;
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++)
[Link](new ArrayList<>());
[Link](0).add(1);
[Link](0).add(2);
[Link](1).add(3);
[Link](1).add(4);
boolean visited[] = new boolean[V];
dfs(0, visited, adj);
}
}

9. String Algorithms - KMP Pattern Matching

class KMP {
void computeLPSArray(String pat, int M, int lps[]) {
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if ([Link](i) == [Link](len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) len = lps[len-1];
else { lps[i] = 0; i++; }
}
}
}
void KMPSearch(String pat, String txt) {
int M = [Link]();
int N = [Link]();
int lps[] = new int[M];
computeLPSArray(pat, M, lps);
int i = 0, j = 0;
while (i < N) {
if ([Link](j) == [Link](i)) {
i++; j++;
Algorithm Lab Codes in Java

}
if (j == M) {
[Link]("Found pattern at index " + (i-j));
j = lps[j-1];
} else if (i < N && [Link](j) != [Link](i)) {
if (j != 0) j = lps[j-1];
else i++;
}
}
}
}

Common questions

Powered by AI

The merge function in the MergeSort class is designed to merge two sorted subarrays, L and R, back into the main array arr, maintaining the order. It first creates temporary arrays L and R to store elements of the two halves. The merging process uses three pointers: i for indexing into L, j for R, and k for arr. It compares elements of L and R, placing the smaller one into arr. After exhausting one of the halves, it copies the remaining elements of the other half into arr. This ensures that the entire section from l to r of arr is sorted .

A divide-and-conquer approach is suitable for the Maximum Subarray problem because it breaks the problem into smaller subproblems, solves each recursively, and combines their solutions. This approach effectively handles overlapping subproblems by computing the maximum subarray that includes the midpoint and comparing it with maximum subarrays on the left and right of the midpoint, ensuring all possible subarrays are considered. The use of recursive splitting and cross-merge steps efficiently finds the solution in O(n log n) time, making it more suitable than the naive O(n^2) approach for large inputs .

The computeLPSArray function supports the efficiency of the KMP algorithm by pre-processing the pattern to determine the longest prefix which is also a suffix for each sub-pattern. This pre-processing allows the main search phase to skip sections of the text that have been unsuccessfully matched against certain sections of the pattern, thus avoiding redundant comparisons. It reduces the complexity of pattern matching from O(nm) in the naive solution to O(n+m) in KMP, significantly improving efficiency for large texts and patterns .

The greedy strategy in the Activity Selection problem drives the algorithm to always pick the next activity that finishes the earliest among the rest, given that there is no overlap with previously selected activities. This approach focuses on making the locally optimal choice at each step, hoping to find the global optimum. By selecting activities that free up time availability the soonest, the algorithm maximizes the number of non-overlapping activities that can be scheduled, ensuring an optimal solution for this problem class .

The DFS class uses a recursive depth-first search approach, which involves visiting a node, marking it as visited, and then recursively exploring all its unvisited adjacent nodes. This traversal method uses a boolean array to track visited nodes, ensuring that each node is processed exactly once. By recursively visiting each node's neighbors before backtracking, DFS guarantees all nodes connected to the starting node are reached, thus covering the entire component of the graph .

The Dijkstra class selects the next vertex with the smallest tentative distance using the minDistance function. This function iterates over all vertices that have not yet been included in the shortest path tree set (sptSet) and determines the vertex with the minimum distance value from the source. In each iteration, it updates the distance values for adjacent vertices of the picked vertex if a shorter path is found by including this vertex. Thus, each step greedily chooses the vertex with the shortest known path from the source .

Backtracking plays a crucial role in solving the N-Queens problem by systematically exploring possible placements of queens on the board while ensuring constraints are met. In the NQueens class, backtracking allows the program to place a queen in a column and recurse to explore further placements. If a placement leads to no valid solution, the algorithm backtracks and tries the next possible row in the previous column. This method ensures all possible configurations are systematically explored while discarding invalid paths early, hence reducing the search space efficiently .

Binary Search requires the input array to be sorted because it operates on the principle of checking the middle element of a specified range and determining if the target element is greater or lesser. If the array is sorted, this allows the algorithm to eliminate half of the possible search space on each iteration. Without a sorted array, the assumptions about the position of the target relative to the middle element would be invalid, leading to incorrect search results .

Dynamic programming optimizes the 0/1 Knapsack Problem by storing previously computed results of subproblems in a matrix and building up solutions to larger subproblems. Unlike a naive recursive approach which would try every possible subset leading to exponential time complexity, dynamic programming ensures each subproblem is solved only once, leading to a more efficient O(nW) time complexity, where n is the number of items and W the capacity. This eliminates the redundancy of solving the same problem multiple times and allows tackling larger inputs effectively .

The KMP (Knuth-Morris-Pratt) pattern matching algorithm reduces the number of comparisons by using a preprocessing step to construct the longest prefix suffix (LPS) array. The LPS array allows the algorithm to skip unnecessary comparisons by identifying the number of characters that can be aligned when a mismatch occurs. This means that instead of starting from the next character after a mismatch, the algorithm uses information about the pattern itself to skip comparison steps, allowing it to achieve an O(n + m) time complexity versus the naive O(n*m).

You might also like