Question: Using C++, form an insertion sort and merge sort for an array of random elements. Find the time it takes to execute each sort in
Using C++, form an insertion sort and merge sort for an array of random elements. Find the time it takes to execute each sort in milliseconds. Use 4 data set sizes. Results will be based on execution time for each sort. The size should have a regular increment. For example, using a regular increment of 10,000, you might have sizes of 10,000, 20,000, 30,000, and 40,000. Your data size will be chosen based upon the ability to obtain meaning results.
This is the code I came up with and I'm completely lost. Please help! You can create your own code, this was just my basis.
#include
using namespace std;
// Forward declarations of functions. void pressAnyKey(); void displayArray(int array[], int length); void randomizeArray(int array[], int length); int insertionsort(int array[], int n);
// Global variables and constants. const int LENGTH = 10000; // The length of our demonstration array.
int main() { int demo[LENGTH]; // Declare, initialize, and display array. displayArray(demo, LENGTH);
randomizeArray(demo, LENGTH); // Randomize values in array and display. displayArray(demo, LENGTH); pressAnyKey();
insertionsort; printArray;
pressAnyKey(); // End main function and end program. return 0; }
// Display values of array - each on their own line. void displayArray(int array[], int length) { int i = 0; while (i < length) { cout << array[i] << " "; i++; } cout << endl; }
// Give a random value to each element of the array. void randomizeArray(int array[], int length) { srand((unsigned)time(NULL)); // Seed random number generator.
int i = 0; do { array[i] = rand() % 100 + 1; // A random number in the range of 1 to 100 is assigned. i++; } while (i < length); }
int insertionsort(int array[], int n) { return 0; }
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1;
//* Move elements of arr[0..i-1], that aregreater than key, to one position ahead of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf(" "); }
// Utility functions. // Press any key to continue. void pressAnyKey() { cout << "Press any key to continue" << endl; _getch(); // Waits and gets next character entered. }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
