0% 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.
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)
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.
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

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;

while (i < n1 && j < n2) {


if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = leftArray[i];
i++;
k++;
}

while (j < n2) {


arr[k] = rightArray[j];
j++;
k++;
}
}
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy