Question

Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers...

  1. Implement functions for insertion sort, quicksort, heapsort and merge sort that input an array of integers and sort it in-place.
  2. Write a program that generates random integer arrays (hint: use seed appropriately to avoid generating same sequences) of lengths 10, 100, 1000, 10,000, 100,000, 1000,000, and then sorts each using each of the sorting functions from (a), and measures the time in nanoseconds. The program will repeat this process 30 times and will compute the average execution time for each (arraysize,sorting-function) pair, over these 30 iterations. Finally, the program will output all these numbers in a readable format, e.g., as a table, in the PDF file.
  3. Are your computed numbers reasonable given your knowledge of the asymptotic complexity of each sorting algorithm? Explain. Put your answer in the PDF file.

Note:

  • Complete all the functions for a and b in exercise_3.cpp, then submit this cpp file.

CODE:

#include <chrono>

#include <cstdio>

/*

* Implement the 4 in-place sort functions for exercise 3.a.

*/

void insertion_sort(int array[], size_t size) {

  // Implement here

}

void quick_sort(int array[], size_t size) {

  // Implement here

}

void heap_sort(int array[], size_t size) {

  // Implement here

}

void merge_sort(int array[], size_t size) {

  // Implement here

}


/*

* Generate random integers for exercise 3.b

*/

int *random_ints(size_t size) {

  int *numbers = new int[size];

  // Generate random numbers here

  return numbers;

}

/* Here is an example to measure a function's running time in nanoseconds

long long time_example() {

  auto start_time = std::chrono::high_resolution_clock::now();

  // Run function to measure the time in nanoseconds

  auto end_time = std::chrono::high_resolution_clock::now();

  auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(

      end_time - start_time);

  return elapsed.count();

}

*/

Homework Answers

Answer #1

Solution :

Following are the commented C++ code for both the part :

3.a)

#include <chrono>
#include <cstdio>
#include <time.h>
/*

* Implement the 4 in-place sort functions for exercise 3.a.

*/

void insertion_sort(int array[], size_t size) {

  // Implement here
  
   for (int i = 1; i < size; i++) {
        int elem = array[i];
        int j    = i - 1;

        // Compare elem with the elements before it, and swap if necessary. 
        // Swapping is done by repeatedly moving the elements one unit back.
        while (j >= 0 and array[j] > elem) {
            array[j + 1] = array[j]; 
            j--;
        }
        array[j + 1] = elem;
    }

}
int partition (int arr[], int low, int high) 
{ 
    int 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 quickSorthelp(int arr[], int low, int high) 
{ 
    if (low < high) 
    { 
        /* pi is partitioning index, arr[p] is now 
           at right place */
        int p = partition(arr, low, high); 
  
        // Separately sort elements before 
        // partition and after partition 
        quickSorthelp(arr, low, p - 1); 
        quickSorthelp(arr, p + 1, high); 
    } 
} 
void quick_sort(int array[], size_t size) {

  // Implement here
    quickSorthelp(array,0,size-1);  

}

void heapify(int arr[], int n, int i) 
{ 
    int largest = i; // Initialize largest as root 
    int l = 2 * i + 1; // left = 2*i + 1 
    int r = 2 * i + 2; // right = 2*i + 2 
  
    // If left child is larger than root 
    if (l < n && arr[l] > arr[largest]) 
        largest = l; 
  
    // If right child is larger than largest so far 
    if (r < n && arr[r] > arr[largest]) 
        largest = r; 
  
    // If largest is not root 
    if (largest != i) { 
        swap(arr[i], arr[largest]); 
  
        // Recursively heapify the affected sub-tree 
        heapify(arr, n, largest); 
    } 
} 
  
void heap_sort(int array[], size_t size) {
    
  // Implement here
  // Build heap (rearrange array) 
    for (int i = size / 2 - 1; i >= 0; i--) 
        heapify(array, size, i); 
  
    // One by one extract an element from heap 
    for (int i = size - 1; i >= 0; i--) { 
        // Move current root to end 
        swap(array[0], array[i]); 
  
        // call max heapify on the reduced heap 
        heapify(array, i, 0); 
    } 
  

}

void merge(int arr[], int l, int m, int r)
{
    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(int i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for(int j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
 
    // Merge the temp arrays back into arr[l..r]
     
    // Initial index of first subarray
    int i = 0; 
     
    // Initial index of second subarray
    int j = 0; 
     
    // Initial index of merged subarray
    int k = l;
     
    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++;
    }
}
 
// l is for left index and r is 
// right index of the sub-array
// of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {
         
        // Same as (l+r)/2, but avoids 
        // overflow for large l and h
        int m = l + (r - l) / 2;
 
        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
 
        merge(arr, l, m, r);
    }
}
void merge_sort(int array[], size_t size) {

  mergeSort(array,0,size-1);

}

}

3.b)

#include <chrono>
#include <cstdio>
#include<ctime>

/*

* Generate random integers for exercise 3.b

*/
int *random_ints(size_t size) {

  int *numbers = new int[size];

  //seeding
  srand(time(0));
  // Generate random numbers here
  for(int i=0;i<size;i++)
  numbers[i]=rand()%(INT_MAX);

  return numbers;

}

void test()
{
    //for insertion sort
    int array1[10]=random_ints(10);
    auto start_time = std::chrono::high_resolution_clock::now();
    insertion_sort(array1,10);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array2[100]=random_ints(100);
    auto start_time = std::chrono::high_resolution_clock::now();
    insertion_sort(array2,100);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array3[1000]=random_ints(1000);
    auto start_time = std::chrono::high_resolution_clock::now();
    insertion_sort(array3,1000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array4[10000]=random_ints(10000);
    auto start_time = std::chrono::high_resolution_clock::now();
    insertion_sort(array4,10000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    //for quick sort
    int array5[10]=random_ints(10);
    auto start_time = std::chrono::high_resolution_clock::now();
    quick_sort(array5,10);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array6[100]=random_ints(100);
    auto start_time = std::chrono::high_resolution_clock::now();
    quick_sort(array6,100);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array7[1000]=random_ints(1000);
    auto start_time = std::chrono::high_resolution_clock::now();
    quick_sort(array7,1000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array8[10000]=random_ints(10000);
    auto start_time = std::chrono::high_resolution_clock::now();
    quick_sort(array8,10000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    //for heap sort
    int array9[10]=random_ints(10);
    auto start_time = std::chrono::high_resolution_clock::now();
    heap_sort(array9,10);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array10[100]=random_ints(100);
    auto start_time = std::chrono::high_resolution_clock::now();
    heap_sort(array10,100);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array11[1000]=random_ints(1000);
    auto start_time = std::chrono::high_resolution_clock::now();
    heap_sort(array11,1000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array12[10000]=random_ints(10000);
    auto start_time = std::chrono::high_resolution_clock::now();
    heap_sort(array12,10000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();

    //for merge sort    
    int array13[10]=random_ints(10);
    auto start_time = std::chrono::high_resolution_clock::now();
    merge_sort(array13,10);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array14[100]=random_ints(100);
    auto start_time = std::chrono::high_resolution_clock::now();
    merge_sort(array14,100);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array15[1000]=random_ints(1000);
    auto start_time = std::chrono::high_resolution_clock::now();
    merge_sort(array15,1000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    int array16[10000]=random_ints(10000);
    auto start_time = std::chrono::high_resolution_clock::now();
    merge_sort(array16,10000);
    auto end_time = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
        end_time - start_time);
    cout<<"\n"<< elapsed.count();
    
    
}
  
Know the answer?
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
Similar Questions
1.) Generate an array of 10 random numbers between 1 - 100 2.) Copy the array...
1.) Generate an array of 10 random numbers between 1 - 100 2.) Copy the array to a temp array 3.) Call each of the methods to sort (bubble, selection, insertion, quick, merge), passing it the array 4.) In-between the calls, you are going to refresh the array to the original numbers. 5.) Inside of each sorting method, you are going to obtain the nanoseconds time, before and after the method Subtract the before time from the after time to...
out of the following four: 1.Bubble sort 2. Insertion sort 3. Quicksort 4. Mergesort a. Which...
out of the following four: 1.Bubble sort 2. Insertion sort 3. Quicksort 4. Mergesort a. Which sorting methods perform best and worst for data sizes ≥ 25,000 when the input data is random? b. Which sorting methods perform best and worst for data sizes ≥ 25,000 when the input data is 90% sorted? c. Which sorting methods perform best and worst for data sizes ≥ 25,000 when the input data is reverse sorted? d. Which sorting methods perform best and...
Using the C programming language implement Heapsort in the manner described in class. Here is some...
Using the C programming language implement Heapsort in the manner described in class. Here is some example code to use as a guideline. Remember, you need only implement the sort algorithm, both the comparison and main functions have been provided. /* * * after splitting this file into the five source files: * * srt.h, main.c, srtbubb.c, srtinsr.c, srtmerg.c * * compile using the command: * * gcc -std=c99 -DRAND -DPRNT -DTYPE=(float | double) -D(BUBB | HEAP | INSR |...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid. Overload the operator+ so that it adds two bigint together. Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first...
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort...
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort algorithm to sort this list. Fill in this table with each iteration of the loop in the selection sort algorithm. Mark the place from which you are looking for the 'next smallest element'. In this display, the upper numbers are the indices, the lower numbers are in the corresponding positions. Use the several rows provided to show the sequence of steps. 0 1 2...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF...
WRITE C++ PROGRAM FOR 1,2,3,4 PARTS of question, DO ADD COOMENTS AND DISPLAY THE OUTPUT OF A RUNNING COMPILER QUESTION: 1) Fibonacci sequence is a sequence in which every number after the first two is the sum of the two preceding ones. Write a C++ program that takes a number n from user and populate an array with first n Fibonacci numbers. For example: For n=10 Fibonacci Numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 2): Write...
Must be written in c++: This problem solely involves your demonstration of the proper usage of...
Must be written in c++: This problem solely involves your demonstration of the proper usage of C++ STL std::list<int> Below you will be given four total functions to develop (two are listed here, two separately after) Put all four of your functions in the same single source code file Submit ONLY your one source code CPP file online Submitting two or three or more separate CPP files will lose points (1) The first function you will need to implement is...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
My assignment: Triplet Template Class Directions: Define a template class for a generic triplet. The private...
My assignment: Triplet Template Class Directions: Define a template class for a generic triplet. The private data member for the triplet is a generic array with three elements. The triplet ADT has the following functions:  default constructor  explicit constructor: initialize the data member using parameters  three accessors (three get functions) which will return the value of each individual element of the array data member  one mutator (set function) which will assign values to the data member...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop...
STRICT DOWNVOTE IF NOT DONE FULLY, WILL REPORT ALSO IF COPY PASTED OR MODIFIED ANSWER Develop a class, using templates, to provide functionality for a set of recursive functions. The functions specified as recursive must be written recursively (not iterativly). The UML class specifications are provided below. A main will be provided. Additionally, a make file will need to be developed and submitted. ● Recursion Set Class The recursion set template class will implement the template functions. recursionSet -length: int...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT