Question: Based on the performance results obtained in Problem-3, modify the merge sort algorithm such that when the array size gets small enough, you would invoke
Based on the performance results obtained in Problem-3, modify the merge sort algorithm such that when the array size gets small enough, you would invoke insertion sort instead of invoking merge sort (hint: you have to change the base condition in the recursion). Instead of hardcoding the array size make it a variable that you can pass as an argument to the merge sort method and test this cutoff value with at least four different values.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException { String Filename[] = new String[] { "input_100.txt", "input_1000.txt", "input_5000.txt", "input_10000.txt", "input_50000.txt", "input_100000.txt", "input_500000.txt" }; int[] size = {100,1000,5000,10000,50000,100000,500000}; // create Double times and file length double times[] = new double[Filename.length]; for (int n = 0; n < Filename.length; n++) { long startTime, finishTime, totalTime;
//double array and size of n double[] arr = new double[size[n]]; Scanner number = new Scanner(new File(Filename[n])); for (int i = 0; i < size[n]; ++i) arr[i] = number.nextDouble(); number.close(); // start time and System nano time startTime = System.nanoTime(); insertionsort.insertionSort(arr);
finishTime = System.nanoTime(); totalTime = finishTime - startTime;
times[n] = totalTime; System.out.println("Recorded time : " + times[n] + " nanoseconds to sort file " + Filename[n]); } } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner;
public class Test_MergeSort {
public static void main(String[] args) throws FileNotFoundException {
// provide file relative path String Filename[] = new String[] { "input_100.txt", "input_1000.txt", "input_5000.txt", "input_10000.txt", "input_50000.txt", "input_100000.txt", "input_500000.txt" }; int[] array = { 100, 1000, 5000, 10000, 50000, 100000, 500000 };
// create Double times and file length double times[] = new double[Filename.length]; for (int n = 0; n < Filename.length; n++) { long startTime, finishTime, totalTime;
// double array and size of n double[] arr = new double[array[n]]; Scanner number = new Scanner(new File(Filename[n])); for (int i = 0; i < array[n]; ++i) arr[i] = number.nextDouble(); number.close(); // start time and System nano time startTime = System.nanoTime(); MergeSort.sort(arr, 0, arr.length);
finishTime = System.nanoTime(); totalTime = finishTime - startTime;
times[n] = totalTime; System.out.println("Recorded time : " + times[n] + " nanoseconds to sort file " + Filename[n]); } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
