Question

In: Computer Science

Using C ++, Given the following data set N =9 12 3 78 89 22 31...

Using C ++, Given the following data set N =9

12 3 78 89 22 31 5 20 14

a ) sort the data using: Insertion and Selection sorts

Determine thee number of comparisons and the number of moved for every sort.

b) Sort the data using Heap and bubble sort, show all steps

Solutions

Expert Solution

Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

// C++ program for implementation of selection sort  
#include <bits/stdc++.h> 
using namespace std; 
  
void swap(int *xp, int *yp)  
{  
    int temp = *xp;  
    *xp = *yp;  
    *yp = temp;  
}  
  
void selectionSort(int arr[], int n)  
{  
    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]);  
    }  
}  
  
/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i=0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  
  
// Driver program to test above functions  
int main()  
{  
    int arr[] = {12, 3, 78, 89, 22, 31, 5, 20, 14};  
    int n = sizeof(arr)/sizeof(arr[0]);  
    selectionSort(arr, n);  
    cout << "Sorted array: \n";  
    printArray(arr, n);  
    return 0;  
}  

Insertion Sort

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

// C++ program for insertion sort

#include <bits/stdc++.h>

using namespace std;

/* Function to sort an array using insertion sort*/

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 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;

    }

}

// A utility function to print an array of size n

void printArray(int arr[], int n)

{

    int i;

    for (i = 0; i < n; i++)

        cout << arr[i] << " ";

    cout << endl;

}

/* Driver code */

int main()

{

    int arr[] = {12, 3, 78, 89, 22, 31, 5, 20, 14};

    int n = sizeof(arr) / sizeof(arr[0]);

    insertionSort(arr, n);

    printArray(arr, n);

    return 0;

}

Heap Sort

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

// C++ program for implementation of Heap Sort
#include <iostream>
using namespace std;

// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
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);
   }
}

// main function to do heap sort
void heapSort(int arr[], int n)
{
   // Build heap (rearrange array)
   for (int i = n / 2 - 1; i >= 0; i--)
       heapify(arr, n, i);

   // One by one extract an element from heap
   for (int i = n - 1; i >= 0; i--) {
       // Move current root to end
       swap(arr[0], arr[i]);

       // call max heapify on the reduced heap
       heapify(arr, i, 0);
   }
}

/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
   for (int i = 0; i < n; ++i)
       cout << arr[i] << " ";
   cout << "\n";
}

// Driver program
int main()
{
   int arr[] = {12, 3, 78, 89, 22, 31, 5, 20, 14};
   int n = sizeof(arr) / sizeof(arr[0]);

   heapSort(arr, n);

   cout << "Sorted array is \n";
   printArray(arr, n);
}

Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

// C++ program for implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
  
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
  
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
  
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
  
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
  
// Driver code
int main()
{
int arr[] = {12, 3, 78, 89, 22, 31, 5, 20, 14};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
return 0;
}


Related Solutions

Given the following data set N =9 12 3 78 89 22 31 5 20 14...
Given the following data set N =9 12 3 78 89 22 31 5 20 14 a ) sort the data using: Insertion and Selection sorts Determine thee number of comparisons and the number of moved for every sort. b) Sort the data using Heap and bubble sort, show all steps
For the following data set, 5, 9, 12, 15, 19, 21, 22, 22, 24, 26, 27,...
For the following data set, 5, 9, 12, 15, 19, 21, 22, 22, 24, 26, 27, 27, 31, 33, 33, 34, 37, 38, 60, 70 a) Find the quartiles Q1 Q2 Q3 b) Find the five number summary c) Find the interquartile range (IQR) IQR = d) Find the lower limit LL = e) Find the upper limit UL = f) Identify the potential outliers (Separate each outlier with a comma. Write NPO if there is no potential outlier) The...
You have been given the following set of keys 12, 45, 1, 9, 67, 230, 78,...
You have been given the following set of keys 12, 45, 1, 9, 67, 230, 78, 64, 450, 436, 123, 6, 12, 90 Use insertion to sort the elements in ascending and descending order ( show the steps)     [5 Marks] Using heaps, show how the keys can be sorted in ascending and descending order ( show the steps)      [5 Marks] Using Big O, derive the space and time complexity of insertion sort and heap sort algorithms above
The following set of data is from a sample of n= 7: 12 7 4 9...
The following set of data is from a sample of n= 7: 12 7 4 9 0 7 20 A) compute the mean, median, and mode. B) compute the range, variance, standard deviation, and coefficient of variation C) compute the Z score of 0 and 20. Are there any outliers? D) compute the first quartile, the third quartile, and the interquartile range
Given the data set below 25 52 67 23 78 89 57 90 32 77 45...
Given the data set below 25 52 67 23 78 89 57 90 32 77 45 48 62 54 94 69 46 79 40 33 21 57 84 54 23 34 68 63 61 76 87 78 39 50 70 60 32 65 73 45 28 82 66 79 71 80 46 66 24 90 A)What is the probability of an impossible even? B) What is the probability of a certain event? C) find the approximate mean using the Frequency...
5. Given the data set A = {9, 5, 16, 4, 32, 8, 12, 9, 11,...
5. Given the data set A = {9, 5, 16, 4, 32, 8, 12, 9, 11, 15, 5, 9, 18, 10}, which is the data of an entire population of subjects: a. Calculate the arithmetic mean (5 pts) b. Find the median (5 pts) c. Find the mode (5 pts) d. Calculate the range (5 pts) e. Calculate the interquartile range (5 pts) f. Calculate the mean deviation (5 pts) g. Calculate the variance (5 pts) h. Calculate the standard...
For the following data set, X: 9, 6, 8, 3, 8, 9, 3, 4, 3, 7:...
For the following data set, X: 9, 6, 8, 3, 8, 9, 3, 4, 3, 7: Calculate: 1. Variance 2. Mode 3. Mean 4. Mean Average Deviation (MAD) about the mean 5. Median
4. [22 pts] For the function ?(?) = 2?5 − 9?4 + 12?3 − 12?2 +...
4. [22 pts] For the function ?(?) = 2?5 − 9?4 + 12?3 − 12?2 + 10? − 3 answer the following: a. [2 pts] Determine whether the function represents a polynomial. Justify your answer. b. [4 pts] Determine whether the function satisfies the Intermediate Value Theorem on the interval [0, 5]. Justify your answer. c. [2 pts] Determine the number (quantity) of complex zeros that the function has, provided the each zero is counted by its multiplicity. d. [4...
Find the lower fence for the following data set: 45, 34, 27, 78, 42, 64, 78...
Find the lower fence for the following data set: 45, 34, 27, 78, 42, 64, 78 Find the upper fence for the following data set: 3, 19, 47, 18, 23, 34, 45, 27, 10, 7
Using the following data set: 10, 5, 2, 7, 20, 3, 13, 15, 8, 9 Apply...
Using the following data set: 10, 5, 2, 7, 20, 3, 13, 15, 8, 9 Apply the Merge sort algorithm. [Show to sorting process of the first half only] Apply the Quick sort algorithm [Show the first partitioning implementation]
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT