Answer to Question #230749 in C++ for Skye Jordan

Question #230749

2. Write a C++ program to show the sorting methods based on user input with the explanation. You can choose any TWO (2) of the sorting methods as below.


- Selection

- Insertion

- Merge

- Bubble

- Quick


1
Expert's answer
2021-08-29T08:20:02-0400
#include <iostream>
using namespace std;


void swap(int *xp, int *yp)
{
    // swap address contents
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
void selectionSort(int arr[], int n)
{
    //implements selection sort
    int i, j, min_idx;
 
    for (i = 0; i < n-1; i++)
    {
        min_idx = i;
        for (j = i+1; j < n; j++)
        if (arr[j] < arr[min_idx])
            min_idx = j;
 
        swap(&arr[min_idx], &arr[i]);
    }
}
void bubbleSort(int arr[], int n)
{
    //implementation of bubble sort
    int i, j;
    for (i = 0; i < n-1; i++)   
        for (j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
                swap(&arr[j], &arr[j+1]);
}


void printArray(int arr[], int size)
{
    // print an array
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}


int main()
{
    int *arr1, *arr2, n;
    cout<<"Input size of array: ";
    cin>>n;
    arr1 = new int[n];
    arr2 = new int[n];
    cout<<"Input array elements (Integers)\n";
    for(int i = 0; i < n; i++){
        cin>>arr1[i];
        arr2[i] = arr1[i];
    }
    bubbleSort(arr1, n);
    selectionSort(arr2, n);
    cout<<"Array sorted with bubble sort: \n";
    printArray(arr1, n);
    cout<<"Array sorted with selection sort: \n";
    printArray(arr2, n);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS