In: Computer Science
Selection Sort Programmatically Implement in C++ the necessary program that does the following: Asks the user and gets at least 5 whole numbers as user input from the keyboard and stores them in an array Displays the numbers from the array on the screen Sorts the numbers in the array using SELECTION SORT Algorithm Displays the sorted numbers on the screen from the array Save your code file as "yourLastname_Firstname_SelectionSort.cpp" and submit your .cpp file. NOTE: This assignment needs only one .cpp file
/* C++ program to do selection sort*/
/* include necessary header files */
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n){
/*
function for performing selection sort
@Param: An array and an integer n which is size of array
Return:
*/
/* declare variables */
int i, j, min, t;
/* for each in element in the array move the element towards bondary */
for (i = 0; i < n-1; i++){
/* Find the minimum element */
min = i;
for(j = i+1; j < n; j++){
if (arr[j] < arr[min])
min = j;
}
/* swap the elements */
t = arr[min];
arr[min] = arr[i];
arr[i] = t;
}
}
/* Function to print an array */
void display(int arr[], int n){
/*
function to display array
@Param: An array and an integer n which is size of array
Return:
*/
/* display */
for (int i=0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver code */
int main() {
/* declare variable(s) */
int n = 0;
/* keep asking until no of elements >= 5 */
while(n < 5){
cout<<"Enter no of elements (at least 5): ";
cin>>n;
}
/* declare an array of size n */
int arr[n] = {0};
/* take input of numbers */
cout<<"Enter the numbers: ";
for(int i = 0; i < n; i++)
cin>> arr[i];
/* display the array */
cout << "\nInput array: ";
display(arr, n);
cout<<endl;
/* calll function to do selection sort */
selectionSort(arr, n);
/* display the sorted array */
cout << "\nSorted array: ";
display(arr, n);
return 0;
}
___________________________________________________________________
___________________________________________________________________
Enter no of elements (at least 5): 2
Enter no of elements (at least 5): 4
Enter no of elements (at least 5): 6
Enter the numbers: 10 7 8 4 20 5
Input array: 10 7 8 4 20 5
Sorted array: 4 5 7 8 10 20
___________________________________________________________________
Note: If you have
queries or confusion regarding this question, please leave a
comment. I would be happy to help you. If you find it to be useful,
please upvote.