The document contains a Java implementation of the Merge Sort algorithm. It includes methods for generating a random array, performing the merge sort, and merging two sorted subarrays. The main method tests the sorting on arrays of varying sizes with random integers between 0 and 99.
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 ratings0% found this document useful (0 votes)
3 views
daa13
The document contains a Java implementation of the Merge Sort algorithm. It includes methods for generating a random array, performing the merge sort, and merging two sorted subarrays. The main method tests the sorting on arrays of varying sizes with random integers between 0 and 99.
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
CODE:
import java.util.*;
public class MergeSort {
public static void main(String[] args) { int[] nValues = { 6000, 5500, 6500, 7000, 5100 }; for (int n : nValues) { int[] arr = generateRandomArray(n); mergeSort(arr, 0, arr.length - 1); for (int i = 0; i < arr.length; ++i) System.out.print(arr[i] + " "); } }
public static int[] generateRandomArray(int n) {
int[] arr = new int[n]; Random random = new Random(); for (int i = 0; i < n; i++) { arr[i] = random.nextInt(100); // Generate random integers between 0 and 99 } return arr; }
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) { int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
} }
public static void merge(int[] arr, int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
for (int i = 0; i < n1; i++) {
leftArray[i] = arr[left + i]; } for (int i = 0; i < n2; i++) { rightArray[i] = arr[mid + 1 + i]; } int i = 0, j = 0; int k = left;