C++ Program: Consider a selection sort algorithm which rearranges an array by se
ID: 3602866 • Letter: C
Question
C++ Program:
Consider a selection sort algorithm which rearranges an array by selecting an element in the array and moving it to its proper position. This algorithm finds the location of the smallest element in the unsorted portion of the array and moves it to the top of the unsorted portion of the array. The first time, the smallest item in the entire array is located and moved to position 0. The second time, the smallest item in the array starting from the second element in the array is located and moved to position 1, and so on. Write a C++ program that prompts the user to enter 50 integers and stores them in an array and returns a sorted array using the selection sort algorithm. Use functions whenever possible. Your program must contain at least one function selectionSort that receives the array as parameter and sorts its elements according to the selection sort algorithm Note: Test your program by using the following 50 integers: /* 10 17 23 65 34 6 18 27 35 110 75 25 100 24 19 67 45 88 70 96 41 36 72 150 125 25 77 200 90 166 139 55 31 8 29 119 126 137 34 62 135 121 108 197 45 35 24 1 16 43*/Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
//array is the array of the input numbers
void selectionSort(int array[])
{
for(int i=0;i<50;i++)
{
//intializing minimum Value Index
int minimumValueIndex = i;
//finding the minimum value right of the array starting from index i
for(int j=i+1;j<50;j++)
{
if(array[j]<array[minimumValueIndex])
{
minimumValueIndex = j;
}
}
//now we need to swap the elements MINIMUMVALUE and ARRAY[I] as per the logic of selection sort.
int temp = array[i];
array[i] = array[minimumValueIndex];
array[minimumValueIndex] = temp;
}
}
int main()
{
int array[50];
cout<<"Enter the integers to be sorted:"<<endl;
//number of numbers inputted are 50. (fixed as per the question)
for(int i=0;i<50;i++)
{
cin >> array[i];
}
//calling the Selection Sort function.
selectionSort(array);
cout<<"Sorted integers are as follows:"<<endl;
for(int i=0;i<50;i++)
{
cout<<array[i]<<' ';
}
cout<<endl;
return 0;
}
Input:
Enter the integers to be sorted:
10 17 23 65 34 6 18 27 35 110 75 25 100 24 19 67 45 88 70 96 41 36 72 150 125 25 77 200 90 166 139 55 31 8 29 119 126 137 34 62 135 121 108 197 45 35 24 1 16 43
Output:
Sorted integers are as follows:
1 6 8 10 16 17 18 19 23 24 24 25 25 27 29 31 34 34 35 35 36 41 43 45 45 55 62 65 67 70 72 75 77 88 90 96 100 108 110 119 121 125 126 135 137 139 150 166 197 200
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.