Find number of swaps for sorting - C++
Mon Feb 17 2025 01:47:29 GMT+0000 (Coordinated Universal Time)
Saved by
@Rohan@99
#include <iostream>
using namespace std;
int InsertionSort(int a[], int size)
{
int numberOfSwaps = 0;
for(int i = 1; i < size; ++i)
{
int key = a[i];
int j = i-1;
while(j >= 0 && a[j] > key)
{
a[j+1] = a[j];
--j;
++numberOfSwaps;
}
a[j+1] = key;
}
return numberOfSwaps;
}
void PrintArray(int a[], int size)
{
for(int i = 0; i < size; ++i)
{
cout << a[i] << " ";
}
cout << "\n";
}
int main()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; ++i)
{
cin >> a[i];
}
cout << InsertionSort(a, n);
return 0;
}
content_copyCOPY
Comments