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

nrd 7201) 2. (10 pts) Write a function called \"count_swap\" where the inputs ar

ID: 3699452 • Letter: N

Question

nrd 7201) 2. (10 pts) Write a function called "count_swap" where the inputs are a 1D array of real numbers and an integer representing the size of the array. The function sorts the array in increasing order using the selection sort method and returns an integer representing how many values in the original array were out of place. For example, in the array [1, 8, 5, 12, 7, 3], the numbers 8, 12,7, and 3 were originally out of place so the function returns a count of 4. For each index, if a swap wasn't necessary, then the original value was in the correct place.

Explanation / Answer

#include<iostream.h>
#include<conio.h>

int count_swap(int a[],int size)
{
   int i=0,j=0,pos=0,count=0,temp=0;

   for(i=0;i<size-1;i++)
   {
   pos=i;
   for(j=i;j<size;j++)
   {
   if(a[j]<a[pos])
   pos=j;
   }


   if(pos!=i)
   {
   count++;

   temp=a[i];
   a[i]=a[pos];
   a[pos]=temp;
   }

   }

   for(i=0;i<size;i++)
   cout<<" "<<a[i];

   getch();
   return count;

}


void main()
{
   clrscr();
   int a[6]={1,8,5,12,7,3};
   int x=count_swap(a,6);
   cout<<" no of swaps "<<x;
   getch();


}