Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write code in C++ implementing Selection Sort. Your program should let the us

ID: 3855172 • Letter: 1

Question

1. Write code in C++ implementing Selection Sort. Your program should let the user enter how large of an array they wish to sort, followed by the values they wish to be in the array. It should print the unsorted and sorted array. Start with the bubblesort example from class/notes and replace the bubblesort function with a select sort function.

proceedure SelectionSort(array a, length(A) = n)

for i in 0 to n - 2

maxIndex = i

for j in (i + 1) to (n - 1)

if a[j] > A[maxIndex]

maxIndex = j

tmp = A[i]

A[i] = A[maxIndex]

A[maxIndex] = tmp

Explanation / Answer

#include <iostream>

using namespace std;


int main()
{
   int* arr = NULL;
   int size;
   int minIndex, j, i, temp, min;

   cout << "Enter size of array to sort: ";
   cin >> size;

   arr = new int[size];

   cout << "Enter the elements of the array: ";
   for (int i = 0; i < size; i++)
   {
       cin >> arr[i];
   }

   cout << "The unsorted array is the following: ";
   for (int i = 0; i < size; i++)
   {
       cout << arr[i] << " ";
   }

   // selection sort
   for (int i = 0; i < size - 1; i++)
   {
       min = arr[i];
       minIndex = i;
       for (int j = i+1; j < size; j++)
       {
           if (min > arr[j])
           {
               min = arr[j];
               minIndex = j;
           }
       }
       temp = arr[i];
       arr[i] = arr[minIndex];
       arr[minIndex] = temp;
   }

   cout << " The sorted array is the following: ";
   for (int i = 0; i < size; i++)
   {
       cout << arr[i] << " ";
   }
   cout << endl;
   return 0;

}

OUTPUT:

Enter size of array to sort: 5
Enter the elements of the array: 76 89 32 4 99
The unsorted array is the following: 76 89 32 4 99
The sorted array is the following: 4 32 76 89 99

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote