Merge Sort 23
Merge Sort 23
compute its time complexity. Run the program for varied values of n>5000, and
record the time taken to sort. Plot a graph of the time taken versus n on graph
sheet. The elements can be read from a file or can be generated using the
random number generator. Demonstrate using Java how the divide- and-
conquer method works along with its time complexity analysis: worst case,
average case and best case.
import java.util.Random;
import java.util.Scanner;
public class MergeSort {
static final int MAX = 100000;
static int[] a = new int[MAX];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Max array size: ");
int n = input.nextInt();
Random random = new Random();
for (int i = 0; i < n; i++)
a[i] = random.nextInt(10000);
System.out.println("Input Array is:");
for (int i = 0; i < n; i++)
System.out.println(a[i] + " ");
long startTime = System.nanoTime();
MergeSortAlgorithm(0, n - 1);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("********Sorted Array is***********");
for (int i = 0; i < n; i++)
System.out.println(a[i] + " ");
System.out.println("Time Complexity (ms) for n = " +
n + " is : " + (double) elapsedTime / 1000000);
input.close();
}
if (i > mid)
for (h = j; h <= high; h++)
b[k++] = a[h];
else
for (h = i; h <= mid; h++)
b[k++] = a[h];