0% found this document useful (0 votes)
5 views

Algorithm_Lab_Codes_Java

The document contains Java code implementations for three fundamental algorithms: Merge Sort for sorting, Binary Search for searching, and Activity Selection for optimizing activities. Each algorithm is presented with its respective class and methods, demonstrating how they function. The code snippets provide a practical understanding of these algorithms in a programming context.

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)
5 views

Algorithm_Lab_Codes_Java

The document contains Java code implementations for three fundamental algorithms: Merge Sort for sorting, Binary Search for searching, and Activity Selection for optimizing activities. Each algorithm is presented with its respective class and methods, demonstrating how they function. The code snippets provide a practical understanding of these algorithms in a programming context.

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
You are on page 1/ 2

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 = 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;
}
}

3. Greedy Algorithms - Activity Selection

import java.util.*;
class ActivitySelection {
Algorithm Lab Codes in Java

static class Activity {


int start, end;
Activity(int start, int end) { this.start = start; this.end = end; }
}
static void printMaxActivities(Activity arr[], int n) {
Arrays.sort(arr, Comparator.comparingInt(a -> a.end));
int i = 0;
System.out.println("(" + arr[i].start + ", " + arr[i].end + ")");
for (int j = 1; j < n; j++) {
if (arr[j].start >= arr[i].end) {
System.out.println("(" + arr[j].start + ", " + arr[j].end + ")");
i = j;
}
}
}
}

You might also like