The number of swapping needed to sort numbers 22,7,9,31,19 in ascending order using selection sort is ?
A. 4
B. 3
C. 5
D.6
Answers
6 SWAPS
HOPE IT IS HELPFUL FOR YOU
Given numbers : 22 , 7 , 9 , 31 , 19
After comparison 1, array is : 7 22 9 31 19
First element is sorted.
After comparison 2, array is : 7 9 22 31 19
Second element is also sorted.
After comparison 3, array is : 7 9 19 31 22
Third element is also sorted.
After comparison 4, array is : 7 9 19 22 31
Forth element is also sorted.
And after 4 comparisons 5th element is automatically sorted.
So, sorted list is 7 9 19 22 31
So, number of swapping needed to is 4.
Program of selection sort
#include<iostream>
using namespace std;
int main()
{
int n ;
cout<<"Enter number of elements : ";
cin>>n;
int A[n];
cout<<"Enter elements : "<<endl;
for(int i = 0 ; i < n ; i++)
{
cin>>A[i];
}
cout<<"Unsorted Array "<<endl;
for(int i = 0 ; i < n ; i++)
{
cout<<A[i]<<" " ;
}
cout<<endl;
for(int i = 0 ; i < n-1 ; i++)
{
int min_index = i;
for(int j = i + 1 ; j < n ; j++)
{
if(A[j] < A[min_index])
{
min_index = j;
}
}
int t = A[min_index];
A[min_index] = A[i];
A[i] = t;
}
cout<<"Sorted Array"<<endl;
for(int i = 0 ; i < n ; i++)
{
cout<<A[i]<<" " ;
}
return 0;
}