Hi I am solving this problem for Counting the number of swaps in Insertion sort.
Following is my code:
// 9722. Insertion Sort
// Problem code: CODESPTB
#include "iostream"
using namespace std;
int how_many_swaps(int len, int * arr)
{
int swap_count = 0,j,tmp;
for(int i = 1; i< len ; ++i)
{
j=i;
while(j>0)
{
if(arr[j]<arr[j-1])
{
tmp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=tmp;
++swap_count;
}
j=j-1;
}
}
cout<<"\n";
for(int i=0;i<len;i++)
{
cout<<"\t"<<arr[i];
}
return swap_count;
}
int main(void)
{
int t;
//cout<<"Enter number of testcases ";
cin>>t;
if (t>5) return 0;
unsigned int len;
for (int i=1;i<=t;i++)
{
//cout <<"\nEnter the length of array for test case number " << i << "\t";
cin>>len;
if (len>100000) return 0;
int * arr = new int[len];
//cout <<"\nEnter the numbers in array ";
for (unsigned int j=0;j<len;j++)
{
cin>>arr[j];
}
//cout<<"\n Number of Swaps = " ;
cout<< "\n" << how_many_swaps(len,arr) <<"\n";
delete [] arr;
}
return 0;
}
Not sure why I am getting wrong answer. Can anyone please help