Question

C++ Write a program that can be used to compare Insertion Sort, Merge Sort and Quick...

C++

Write a program that can be used to compare Insertion Sort, Merge Sort and Quick Sort.

Program must:

  • Read an array size from the user, dynamically an array of that size, and fill the array with random numbers
  • Sort the array with the Insertion Sort, MergeSort and QuickSort algorithms studied in class, doing a time-stamp on each sort.

Use your program to measure and record the time needed to sort random arrays of size 5000, 50000, and 500000. For each array size, obtain a printout of the time required for the sorts.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below:

main.cpp

#include <iostream>
#include <stdlib.h>
#include <string>
#include <chrono>
#include <fstream>
#include <sstream>
using namespace std::chrono;
using namespace std;
//swap usign by selection sort
void swap(long *xp, long *yp)
{
   long temp = *xp;
   *xp = *yp;
   *yp = temp;
}

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
   time_t now = time(0);
   struct tm tstruct;
   char buf[80];
   tstruct = *localtime(&now);
   // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
   // for more information about date/time format
   strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

   return buf;
}


/* Function to sort an array using insertion sort*/
void insertionSort(long arr[], int n)
{   cout<<"Insertion sort performance "<<endl;
cout << "Start time : " << currentDateTime() <<endl;
auto start = high_resolution_clock::now();
int i, key, j;
for (i = 1; i < n; i++)
{
   key = arr[i];
   j = i-1;

   /* Move elements of arr[0..i-1], that are
greater 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;
}
//check the time
cout << "End time : " << currentDateTime() <<endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Elapse time : " << duration.count() << " microseconds" << endl;

}


void selectionSort(long arr[], int n)
{
   cout<<"Selection sort performance "<<endl;
   //clock to check time
   cout << "Start time : " << currentDateTime() <<endl;
   auto start = high_resolution_clock::now();
   int i, j, min_idx;

   // One by one move boundary of unsorted subarray
   for (i = 0; i < n-1; i++)
   {
       // Find the minimum element in unsorted array
       min_idx = i;
       for (j = i+1; j < n; j++)
           if (arr[j] > arr[min_idx])
               min_idx = j;


       // Swap the found minimum element with the first element
       swap(&arr[min_idx], &arr[i]);
   }

   cout << "End time : " << currentDateTime() <<endl;
   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   cout << "Elapse time : " << duration.count() << " microseconds" << endl;
}


int partition (long arr[], int low, int high)
{
   float pivot = arr[high]; // pivot
   int i = (low - 1); // Index of smaller element

   for (int j = low; j <= high- 1; j++)
   {
       // If current element is smaller than or
       // equal to pivot
       if (arr[j] <= pivot)
       {
           i++; // increment index of smaller element
           swap(&arr[i], &arr[j]);
       }
   }
   swap(&arr[i + 1], &arr[high]);
   return (i + 1);
}


void quickSort(long arr[], int low, int high)
{
   if (low < high)
   {
       /* pi is partitioning index, arr[p] is now
at right place */
       int pi = partition(arr, low, high);

       // Separately sort elements before
       // partition and after partition
       quickSort(arr, low, pi - 1);
       quickSort(arr, pi + 1, high);
   }
}

void doQuickSort(long arr[], int high){
   cout<<"Quick sort performance "<<endl;
   cout << "Start time : " << currentDateTime() <<endl;
   auto start = high_resolution_clock::now();
   quickSort(arr,0,high);
   cout << "End time : " << currentDateTime() <<endl;
   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   cout << "Elapse time : " << duration.count() << " microseconds" << endl;
}


void copyArrayFunc(long source[],long dest[],int size){

   for(int i=0;i<size;i++){
       dest[i] = source[i];
   }
}


void merge(long arr[], int l, int m, int r)
{
   int i, j, k;
   int n1 = m - l + 1;
   int n2 = r - m;

   /* create temp arrays */
   int L[n1], R[n2];

   /* Copy data to temp arrays L[] and R[] */
   for (i = 0; i < n1; i++)
       L[i] = arr[l + i];
   for (j = 0; j < n2; j++)
       R[j] = arr[m + 1+ j];

   /* Merge the temp arrays back into arr[l..r]*/
   i = 0; // Initial index of first subarray
   j = 0; // Initial index of second subarray
   k = l; // Initial index of merged subarray
   while (i < n1 && j < n2)
   {
       if (L[i] <= R[j])
       {
           arr[k] = L[i];
           i++;
       }
       else
       {
           arr[k] = R[j];
           j++;
       }
       k++;
   }

   /* Copy the remaining elements of L[], if there
are any */
   while (i < n1)
   {
       arr[k] = L[i];
       i++;
       k++;
   }

   /* Copy the remaining elements of R[], if there
are any */
   while (j < n2)
   {
       arr[k] = R[j];
       j++;
       k++;
   }
}
void mergeSort(long arr[], int l, int r)
{
   if (l < r)
   {
       int m = l+(r-l)/2;
       mergeSort(arr, l, m);
       for(int i=l;i<=m;i++){
       }
       mergeSort(arr, m+1, r);

       for(int i=m+1;i<=r;i++){
       }
       merge(arr, l, m, r);
   }
}

void doMergeSort(long arr[], int r)
{
   cout<<"\n\nMerge sort performance "<<endl;
   auto start = high_resolution_clock::now();
   cout << "Start time : " << currentDateTime() <<endl;
   mergeSort(arr,0,r);
   cout << "End time : " << currentDateTime() <<endl;
   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   cout << "Elapse time : " << duration.count() << " microseconds" << endl;
}

int main()
{
   //initialize array of 1000
   long arraySize;
   cout<<"Enter input size : ";
   cin>>arraySize;
   long array[arraySize];
   long copyArray[arraySize];
   //set all to zero
   for(int i=0;i<arraySize;i++){
       array[i] =rand()%100000;
   }
   copyArrayFunc(array,copyArray,arraySize);

   insertionSort(copyArray,arraySize);
   cout<<endl<<endl<<endl;
   copyArrayFunc(array,copyArray,arraySize);
   selectionSort(copyArray,arraySize);
   cout<<endl<<endl<<endl;
   copyArrayFunc(array,copyArray,arraySize);
   doQuickSort(copyArray,arraySize-1);
   copyArrayFunc(array,copyArray,arraySize);
   doMergeSort(copyArray,arraySize-1);


   return 0;
}

output:

Add a comment
Know the answer?
Add Answer to:
C++ Write a program that can be used to compare Insertion Sort, Merge Sort and Quick...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • need help!! java eclipse Write a program to implement bubble sort, insertion sort, selection sort, merge...

    need help!! java eclipse Write a program to implement bubble sort, insertion sort, selection sort, merge sort and quick sort (pivot - first index) algorithms. a) Compute the CPU processing time for all the algorithms for varying input sizes as follows: N-10, 103, 10, 10, and 106 b) Use a random number generator to generate the inputs. Obtain the inputs from the following input ranges: 1- 10, 1 -10, 1 - 10, 1 12 10 c) Write down your results...

  • Your running times will probably be different than these. Please do a better job with the snipping tool than I did. Jav...

    Your running times will probably be different than these. Please do a better job with the snipping tool than I did. Java program provided: // Student Name Today's Date import java.util.Arrays; import java.util.Random; public class SortTimer {    // Please expand method main() to meet the lab requirements.       // You have the following sorting methods available:    // insertionSort(int[] a);    // selectionSort(int[] a);    // mergeSort(int[] a);    // quickSort(int[] a);    // The array will be in sorted order after the routines are called!   ...

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort...

    This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort Heap Sort You have access to the implementation of all of these sorting algorithms, and you may use what is provided in your text directly. Be sure to cite the source of these implementations in the header of your program. Please maintain the property that these sorting algorithms sort arrays in ascending order. For this homework, you will write a...

  • Write a program in Java that obtains the execution time of selection sort, insertion sort, bubble...

    Write a program in Java that obtains the execution time of selection sort, insertion sort, bubble sort, merge sort, quick sort, and radix sort. Your program should test all sort methods for input sizes of 10000, 20000, 30000, 40000, 50000, and 60000. The selection sort, bubble sort, and radix sort should also be tested for input sizes 100000 and 200000. Your program should create the data that is sorted from randomly generated integers and should output the results in a...

  • 1. Which is the best sorting algorithm for larger arrays if all the items can not...

    1. Which is the best sorting algorithm for larger arrays if all the items can not fit in main memory? selection sort insertion sort quicksort Merge sort 2. Which sorting algorithm sorts items without comparing them? quick sort radix sort merge sort Insertion sort 3 What is the average running time for quicksort? O(n2) O(logn) O(nlogn) O(n) O(n2logn) 4. Examine the steps of the following algorithm and write the name of the algorithm described in the blank provided: Recursively divide...

  • Python Merge sort algorithm...

    Implement MERGE-SORT() algorithm that reads from a file named “inputHW02.txt” a list of double numbers (max = 3,000,000 numbers), sorts those numbers and indicates time consumption. This programming question will address the advantage of using iteration loops over recursive calls as well as using INSERTION-SORT() as a procedure in MERGESORT(). Your program must perform the following actions: 1. Opens the given file name and reads all double numbers. For simplicity, we assume this file only contains numbers and nothing else....

  • Write a program that obtains the execution time of selection sort, radix sort, bubble sort, merge...

    Write a program that obtains the execution time of selection sort, radix sort, bubble sort, merge sort, quick sort, and heap sort for input size 50000, 100,000, 150,000, 200,000, 250,000, and 300,000. Your program should create data randomly and print a table like this: In the same program, obtain the execution time of selection sort, radix sort, bubble sort, and heap sort for input size 2,000,000, 3,000,000, 4,000,000, and 5,000,000. (Hint: You can use the code template below to obtain...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • Java Merge sort algorithm

    Implement MERGE-SORT() algorithm that reads from a file named “inputHW02.txt” a list of double numbers (max = 3,000,000 numbers), sorts those numbers and indicates time consumption. This programming question will address the advantage of using iteration loops over recursive calls as well as using INSERTION-SORT() as a procedure in MERGESORT(). Your program must perform the following actions: 1. Opens the given file name and reads all double numbers. For simplicity, we assume this file only contains numbers and nothing else....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT