In: Computer Science
Using Selection Sort on an any array of size 7, what will be the minimum/maximum number of comparisons and number of exchanges?
1 for i = 1 to A.length-1
2 for j = i+1 to A.length
3 if A[j] < A[i]
4 exchange A[i] with A[j]
Please find the code below .
In selection sort minimum and maximum number of comparisons and swapping is same in all case like worst best and average.
#include <iostream>
using namespace std;
int main()
{
   int array[7];
   for(int i=0;i<7;i++){
       array[i] = rand()%100;
   }
   cout<<"Before sorting"<<endl;
   for(int i=0;i<7;i++){
       cout<<array[i]<<"
";
   }
   cout<<endl;
   int numberOfComparision = 0;
   int numberOfExchng = 0;
   for(int i=0;i<6;i++){
       for(int j=i+1;j<7;j++){
          
numberOfComparision++;
          
if(array[j]<array[i]){
          
    numberOfExchng++;
          
    int tmp = array[i];
          
    array[i] = array[j];
          
    array[j] = tmp;
           }
       }
   }
   cout<<"After sorting"<<endl;
   for(int i=0;i<7;i++){
       cout<<array[i]<<"
";
   }
   cout<<" Number of comparision is :
"<<numberOfComparision<<endl;
   cout<<"Number of exchanges is :
"<<numberOfExchng<<endl;
cout<<endl;
   return 0;
}
output:
