Question

In: Computer Science

C++ --------------------------------------------- Do a comparison of a slow sort with Big O(n2) (selection sort, insertion sort,...

C++
---------------------------------------------

Do a comparison of a slow sort with Big O(n2) (selection sort, insertion sort, or bubble sort) and one faster sort of Big O(n * log n) (mergesort or quicksort). Count the number of moves (a swap counts as one move). With mergesort, you can count the range of the part of the array you are sorting (i.e. last-first+1). Use the code from the textbook (copy from the lecture notes) and put in an extra reference parameter for the count.

The array needs to be 10,000 items and the number of digits should be 4. Use the srand function to set the seed and rand function to generate the numbers (use the BubbleSort support code from the Examples, chapter 11). For instance:

srand(seed);

for (int x = 0; x < 10000; x++)

    ary[x] = rand() % 10,000;

Would fill the array. Note: do NOT use the "srand(time(NULL)):". You need to recreate the array to be resorted yet again. Note: you can use the sortSupport code on Canvas.

Call the slow sort first, print out the number of moves and the first 10 and last 10 values, fill the array again using the same seed, call the fast sort, and print the number of moves and the first 10 and last 10 values.

The run would look like:

The seed to use is: 39

Bubble sort had 25349145 swaps

The first 10 values: 0 0 0 3 3 6 6 7 7 9

The last 10 values: 9991 9991 9991 9992 9992 9994 9997 9997 9998 9998

Merge sort had 133616 moves

The first 10 values: 0 0 0 3 3 6 6 7 7 9

The last 10 values: 9991 9991 9991 9992 9992 9994 9997 9997 9998 9998
-------------------------------------------------------------------------------------------------------------

#include <cstdlib>
#include <iostream>
#include "sortSupport.h"
#ifndef SORTSUPPORT_CPP
#define SORTSUPPORT_CPP

using namespace std;

// Does seed first
// creates data for the array
template<class ItemType>
void makeArray(ItemType ary[], int max, int seed)
{
        srand(seed);
        for (int index = 0; index < max; index++)
                ary[index] = rand() % MAX_VALUE;
}

// prints the first 10 and last 10 items of an array
template<class ItemType>
void printEnds(ItemType ary[], int max)
{
        cout << "First 10: ";
        for (int index = 0; index < 10; index++)
                cout << ary[index] << " ";
        cout << endl << "Last 10: ";
        for (int index = max - 10; index < max; index++)
                cout << ary[index] << " ";
        cout << endl;
}
#endif
-----------------------------------------------------------------------------

#ifndef SORTSUPPORT_H
#define SORTSUPPORT_H
#include "bubbleSort.h"

const int MAX_VALUE = 10000;
const int MAX_SIZE = 10000;
const int MAX_DIGITS = 4;

template<class ItemType>
void makeArray(ItemType ary[], int max, int seed);

template<class ItemType>
void printEnds(ItemType ary[], int max);

#include "sortSupport.cpp"
#endif
------------------------------------------------------------------------------

#include <iostream>
#include <string>
const int MAX_SIZE = 50;
/** Merges two sorted array segments theArray[first..mid] and 
   theArray[mid+1..last] into one sorted array. 
@pre  first <= mid <= last. The subarrays theArray[first..mid] and    
theArray[mid+1..last] are each sorted in increasing order. 
@post  theArray[first..last] is sorted. 
@param theArray  The given array. 
@param first  The index of the beginning of the first segment in theArray. 
@param mid  The index of the end of the first segment in theArray;   
 mid + 1 marks the beginning of the second segment. 
@param last  The index of the last element in the second segment in theArray. 
@note  This function merges the two subarrays into a temporary    
array and copies the result into the original array theArray. */
template<class ItemType>
void merge(ItemType theArray[], int first, int mid, int last)
{   
ItemType tempArray[MAX_SIZE];  // Temporary array   
// Initialize the local indices to indicate the subarrays  
 int first1 = first;           // Beginning of first subarray   
int last1 = mid;               // End of first subarray  
 int first2 = mid + 1;          // Beginning of second subarray   
int last2 = last;              // End of second subarray   

// While both subarrays are not empty, copy the   
// smaller item into the temporary array  
 int index = first1;            // Next available location in tempArray  
 while ((first1 <= last1) && (first2 <= last2))   
  {      
// At this point, tempArray[first..index-1] is in order      
if (theArray[first1] <= theArray[first2])      
      {         
         tempArray[index] = theArray[first1];         
          first1++;      
       }    
     else     
       {        
        tempArray[index] = theArray[first2];        
         first2++;      
        }  // end if     
  index++;   
   }  // end while   

// Finish off the first subarray, if necessary   
while (first1 <= last1)   
  {      
    // At this point, tempArray[first..index-1] is in order     
  tempArray[index] = theArray[first1];      
  first1++;      
  index++;
   }  // end while  
 // Finish off the second subarray, if necessary   

while (first2 <= last2)   
{      
// At this point, tempArray[first..index-1] is in order      
tempArray[index] = theArray[first2];      
first2++;     
 index++;   
}  // end for   

// Copy the result back into the original array  
 for (index = first; index <= last; index++)      
theArray[index] = tempArray[index];
}  // end merge

/** Sorts the items in an array into ascending order. 
@pre  theArray[first..last] is an array. 
@post  theArray[first..last] is sorted in ascending order. 
@param theArray  The given array. 
@param first  The index of the first element to consider in theArray. 
@param last  The index of the last element to consider in theArray. */

template<class ItemType>
void mergeSort(ItemType theArray[], int first, int last)
{   
if (first < last)   
{      
// Sort each half      
int mid = first + (last - first) / 2; // Index of midpoint      

// Sort left half theArray[first..mid]     
 mergeSort(theArray, first, mid);      

// Sort right half theArray[mid+1..last]      
mergeSort(theArray, mid + 1, last);      

// Merge the two halves     
 merge(theArray, first, mid, last);  
 }  // end if

}  // end mergeSort

int main()
{   
std::string a[6] = {"Z", "X", "R", "K", "F", "B"};  
 mergeSort(a, 0, 5);   
   for (int i = 0; i < 6; i++)      
          std::cout << a[i] << " ";   
  std::cout << std::endl;

}  // end main

/* B F K R X Z  */
 

Solutions

Expert Solution

Comparison of a slow sort with Big O(n2) (selection sort, insertion sort, or bubble sort) and one faster sort of Big O(n * log n) (mergesort or quicksort). Count the number of moves (a swap counts as one move). With mergesort, you can count the range of the part of the array you are sorting (i.e. last-first+1).

Slow Sort Algorithm (Bubble Sort):- Count the number of swaps using code given here:

int bubblesort(int array[], int count) {
    int i, j, temp;
    int swaps = 0; // initialize swap count
    for(i = 0; i < count-1; ++i) {
        for(j=0; j < count-1-i; ++j) {
            if(array[j] > array[j+1]) {
                temp = array[j+1];
                array[j+1] = array[j];
                array[j] = temp;
                swaps++;    // increment swap code after each comparison
            }
        }
    }

    return swaps;
}

Fast Sort Algorithm (Merge Sort): Count the number of moves using code given here:

// C++ program to Count 
// using Merge Sort 
#include <bits/stdc++.h> 
using namespace std; 

int _mergeSort(int arr[], int temp[], int left, int right); 
int merge(int arr[], int temp[], int left, int mid, int right); 

/* This function sorts the input array and returns the number of moves in the array */
int mergeSort(int arr[], int array_size) 
{ 
        int temp[array_size]; 
        return _mergeSort(arr, temp, 0, array_size - 1); 
} 

/* An auxiliary recursive function that sorts the input array and 
returns the number of moves in the array. */
int _mergeSort(int arr[], int temp[], int left, int right) 
{ 
        int mid, moves = 0; 
        if (right > left) { 
                /* Divide the array into two parts and 
                call _mergeSortAndCountInv() 
                for each of the parts */
                mid = (right + left) / 2; 

                /* moves count will be sum of moves in left-part, right-part and number of moves in merging */
                moves += _mergeSort(arr, temp, left, mid); 
                moves += _mergeSort(arr, temp, mid + 1, right); 

                /*Merge the two parts*/
                moves += merge(arr, temp, left, mid + 1, right); 
        } 
        return inv_count; 
} 

/* This funtion merges two sorted arrays and returns moves count in the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right) 
{ 
        int i, j, k; 
        int moves = 0; 

        i = left; /* i is index for left subarray*/
        j = mid; /* j is index for right subarray*/
        k = left; /* k is index for resultant merged subarray*/
        while ((i <= mid - 1) && (j <= right)) { 
                if (arr[i] <= arr[j]) { 
                        temp[k++] = arr[i++]; 
                } 
                else { 
                        temp[k++] = arr[j++]; 
                        moves = moves + (mid - i); 
                } 
        } 

        /* Copy the remaining elements of left subarray (if there are any) to temp*/
        while (i <= mid - 1) 
                temp[k++] = arr[i++]; 

        /* Copy the remaining elements of right subarray (if there are any) to temp*/
        while (j <= right) 
                temp[k++] = arr[j++]; 

        /*Copy back the merged elements to original array*/
        for (i = left; i <= right; i++) 
                arr[i] = temp[i]; 

        return moves; 
} 


Overall code for the comparison of the sort algorithm is given below:

#include <cstdlib>
#include <iostream>
#include <bits/stdc++.h>  
#include "sortSupport.h"
#ifndef SORTSUPPORT_CPP
#define SORTSUPPORT_CPP 

using namespace std;
int _mergeSort(int arr[], int temp[], int left, int right); 
int merge(int arr[], int temp[], int left, int mid, int right); 

int bubblesort(int array[], int count) {
    int i, j, temp;
    int swaps = 0; // initialize swap count
    for(i = 0; i < count-1; ++i) {
        for(j=0; j < count-1-i; ++j) {
            if(array[j] > array[j+1]) {
                temp = array[j+1];
                array[j+1] = array[j];
                array[j] = temp;
                swaps++;    // increment swap code after each comparison
            }
        }
    }

    return swaps;
}


/* This function sorts the input array and returns the number of moves in the array */
int mergeSort(int arr[], int array_size) 
{ 
        int temp[array_size]; 
        return _mergeSort(arr, temp, 0, array_size - 1); 
} 

/* An auxiliary recursive function that sorts the input array and 
returns the number of moves in the array. */
int _mergeSort(int arr[], int temp[], int left, int right) 
{ 
        int mid, inv_count = 0; 
        if (right > left) { 
                /* Divide the array into two parts and 
                call _mergeSortAndCountInv() 
                for each of the parts */
                mid = (right + left) / 2; 

                /* moves count will be sum of moves in left-part, right-part and number of moves in merging */
                inv_count += _mergeSort(arr, temp, left, mid); 
                inv_count += _mergeSort(arr, temp, mid + 1, right); 

                /*Merge the two parts*/
                inv_count += merge(arr, temp, left, mid + 1, right); 
        } 
        return inv_count; 
} 

/* This funtion merges two sorted arrays and returns moves count in the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right) 
{ 
        int i, j, k; 
        int inv_count = 0; 

        i = left; /* i is index for left subarray*/
        j = mid; /* j is index for right subarray*/
        k = left; /* k is index for resultant merged subarray*/
        while ((i <= mid - 1) && (j <= right)) { 
                if (arr[i] <= arr[j]) { 
                        temp[k++] = arr[i++]; 
                } 
                else { 
                        temp[k++] = arr[j++]; 
                        inv_count = inv_count + (mid - i); 
                } 
        } 

        /* Copy the remaining elements of left subarray (if there are any) to temp*/
        while (i <= mid - 1) 
                temp[k++] = arr[i++]; 

        /* Copy the remaining elements of right subarray (if there are any) to temp*/
        while (j <= right) 
                temp[k++] = arr[j++]; 

        /*Copy back the merged elements to original array*/
        for (i = left; i <= right; i++) 
                arr[i] = temp[i]; 

        return inv_count; 
} 


// Does seed first
// creates data for the array
template<class ItemType>
void makeArray(ItemType ary[], int max, int seed)
{
        srand(seed);
        for (int index = 0; index < max; index++)
                ary[index] = rand() % MAX_VALUE;
}

// prints the first 10 and last 10 items of an array
template<class ItemType>
void printEnds(ItemType ary[], int max)
{
        cout << "First 10: ";
        for (int index = 0; index < 10; index++)
                cout << ary[index] << " ";
        cout << endl << "Last 10: ";
        for (int index = max - 10; index < max; index++)
                cout << ary[index] << " ";
        cout << endl;
}
#endif

int main(){
      int seed;
      int arr[10000];
      int max=10000;
      cout << "The seed to use is: ";
      cin >> seed;
    
      makeArray(arr,max,seed);

      int bubbleSort_swap = bubblesort(arr,max);

      cout << "Bubble sort had " << bubbleSort_swap << "swaps";
      
      printEnds(arr,max);

      int mergeSort_swap = mergeSort(arr,max);

      cout << "Merge sort had " << bubbleSort_swap << "moves";

      printEnds(arr,max);
}



Related Solutions

Write a program in C++ to test either the selection sort or insertion sort algorithm for...
Write a program in C++ to test either the selection sort or insertion sort algorithm for array-based lists as given in the chapter. Test the program with at least three (3) lists. Supply the program source code and the test input and output. List1: 14,11,78,59 List2: 15, 22, 4, 74 List3: 14,2,5,44
In C++ Create a program that uses Selection Sort and Insertion Sort for the National Football...
In C++ Create a program that uses Selection Sort and Insertion Sort for the National Football League list of current players. It's going to be a big list(over 1000 names). Please identify, in comments, which part of the code is for the Selection Sort and which part of the code is for Insertion Sort. It must have both. Inputting data from a text file named "Players.txt" Only want the name of the player(first name then last name), their team name,...
For this assignment, find out how to do a bubble sort, selection sort, or insertion sort...
For this assignment, find out how to do a bubble sort, selection sort, or insertion sort in Java. You have the option to choose but you must label (with comments) the algorithm you choose to implement. Convert that algorithm to a generic algorithm and constraint it to only using numerics. Your method should accept an array as a parameter and sort the content of the array. If you wish, you can throw an exception if the contents of the array...
PROVIDE CODE ONLY IN C++ / NO OTHER LANGUAGES PLEASE ADD SELECTION SORT/ INSERTION SORT/ AND...
PROVIDE CODE ONLY IN C++ / NO OTHER LANGUAGES PLEASE ADD SELECTION SORT/ INSERTION SORT/ AND BUBBLE SORT FUNCTION TO THIS PROGRAM #include <iostream> #include<vector> #include <algorithm >   #include <chrono>    #include <ctime> using namespace std; void bubblesSort() { // Please create Bubble Sort function// Make another for Selection Sort and  Insertion Sort } int main() { // empty vector vector<int> data; // data [0], data [1]... data[N-1] <-- end(data) // set of values to test N for (auto N :...
give a good explanation of Bubble sort, Insertion sort, Selection sort, and Quicksort.
give a good explanation of Bubble sort, Insertion sort, Selection sort, and Quicksort.
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers....
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers. Record the time. Run Bubble Check time (compute the processing time) do it 100 times (random numbers) Take the average Insertion: Compare] (some explanations please)
Sort the following set of numbers using bubble sort, insertion sort, and selection sort. Show the...
Sort the following set of numbers using bubble sort, insertion sort, and selection sort. Show the process step-by-step, and find the time complexity in Big-O notation for each method. For sorting, use ascending order. 49, 7, 60, 44, 18, 105
Which of the following sorting algorithms are stable: insertion sort, selection sort, merge sort and quick...
Which of the following sorting algorithms are stable: insertion sort, selection sort, merge sort and quick sort? Give a simple scheme that makes any sorting algorithm stable. How much additional time and space does your scheme entail?
2 real-time examples on the Insertion sort, Bubble sort, Selection sort, Quick sort, Shell sort, Merge...
2 real-time examples on the Insertion sort, Bubble sort, Selection sort, Quick sort, Shell sort, Merge sort, Radix sort, Bucket sort, and Counting sort.
come up with at least 2 real-time examples on the Insertion sort, Bubble sort, Selection sort,...
come up with at least 2 real-time examples on the Insertion sort, Bubble sort, Selection sort, Quick sort, Shell sort, Merge sort, Radix sort, Bucket sort, and Counting sort.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT