Question
Hi I cant seem to solve this question: For the code given below: Implement InsertionSort and MergeSort When testing your code, to sort n elements,
Hi I cant seem to solve this question:
For the code given below:
Implement InsertionSort and MergeSort
When testing your code, to sort n elements, you cin the value of n, and then you cin n different values. The final sorted array will be cout twice, first from InsertionSort, and then from MergeSort.
If you cin a value of n >= 100, the program will automatically populate the array, and will instead report timing information for how long each sorting algorithm took. You should get something comparable to the instructor's program which, on n=100000, reported:
MergeSort on 100000 elements took 0.01997 seconds.
InsertionSort took 26.7788 seconds.
code:
#include
using namespace std;
void InsertionSort(int arr[], int len) { //TO DO }
void Merge(int arr[], int low, int mid, int high) { //Use 'temp' as an array of size high-low+1, for temporary memory. //If you haven't taken 103 yet, you are not expected to understand this. int *temp = new int[high-low+1]; //Your code here. delete [] temp; }
void MergeSort(int arr[], int low, int high) { //TO DO }
//Do not change the main function. int main(int argc, char* argv[]) { int n; clock_t start; double durationI = 0, durationM = 0;
cin >> n; int *arr = new int[n]; int *backup = new int[n]; for (int i = 0; i < n; i++) { if (n < 100) cin >> arr[i]; else arr[i] = n-i; backup[i] = arr[i]; } start = clock(); InsertionSort(arr, n); durationI += ( clock() - start ) / (double) CLOCKS_PER_SEC; if (n < 100) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } for (int j = 0; j < n; j++) arr[j] = backup[j];
start = clock(); MergeSort(arr, 0, n-1); durationM += ( clock() - start ) / (double) CLOCKS_PER_SEC;
if (n < 100) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; }
if (n >= 100) { cout << "MergeSort on " << n << " elements took " << durationM << " seconds." << endl; cout << "InsertionSort took " << durationI << " seconds." << endl; } delete [] arr; delete [] backup; return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started