Check if the array can be sorted with a single swap of 2 elements
write a function that will check if the array can be sorted with a single swap of the values in the array.
For example: array(1,3,5,3,7) must return true,
write a function that will check if the array can be sorted with a single swap of the values in the array.
For example: array(1,3,5,3,7) must return true,
but array(1,3,5,3,4) must return false.
bool fun(int a[], int n)
{
for (int i = 0; i + 1 < n; i++)
{
if (a[i] > a[i+1])
{
int j = i+1;
for (int k = i+2; k < n; k++)
{
if (a[k] < a[j])
{
j = k;
}
}
swap(a[i], a[j]);
int m = i > 0? i-1 : i;
for (; m +1 < n; m++)
{
if (a[m] > a[m+1])
{
return false;
}
}
}
}
return true;
}