Program-03
Program-03
Subject Code:21CS42
Program-03
3. Sort a given set of n integer elements using Merge Sort method and
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. The
elements can be read from a file or can be generated using the random
number generator. Demonstrate using C++/Java how the divide-and-conquer
method works along with its time complexity analysis: worst case, average
case and best case.
• Merge sort is yet another sorting algorithm that falls under the category
of Divide and Conquer technique.
• It is one of the best sorting techniques that successfully build a recursive
algorithm.
In this technique, we segment a problem into two halves and solve them
individually. After finding the solution of each half, we merge them back to
represent the solution of the main problem.
ALGORITHM
1. 1. If p<r
2. 2. Then q → ( p+ r)/2
3. 3. MERGE-SORT (A, p, q)
4. 4. MERGE-SORT ( A, q+1,r)
5. 5. MERGE ( A, p, q, r)
Step-2: After dividing an array into two subarrays, we will notice that it did not
hamper the order of elements as they were in the original array. After now, we will
further divide these two arrays into other halves.
Step-3: Again, we will divide these arrays until we achieve an atomic value, i.e., a
value that cannot be further divided.
Step-4: Next, we will merge them back in the same way as they were broken down.
Step-5: For each list, we will first compare the element and then combine them to
form a new sorted list.
Step-6: In the next iteration, we will compare the lists of two data values and merge
them back into a list of found data values, all placed in a sorted manner.
Example:
Time Complexities:
Best Case Complexity: The merge sort algorithm has a best-case time complexity
of O(n*log n) for the already sorted array.
Average Case Complexity: The average-case time complexity for the merge sort
algorithm is O(n*log n), which happens when 2 or more elements are jumbled, i.e.,
neither in the ascending order nor in the descending order.
Worst Case Complexity: The worst-case time complexity is also O(n*log n), which
occurs when we sort the descending order of an array into the ascending order.
PROGRAM
import java.util.Random;
import java.util.Scanner;
k++;
}
else {
temp[k] = a[j];
j++;
k++;
}
}
while(i<=mid) {
temp[k] = a[i];
i++;
k++;
}
while(j<=high) {
temp[k] = a[j];
j++;
k++;
}
for(k = low; k<=high; k++) {
a[k] = temp[k];
}
}
OUTPUT