#C10318. One Swap Sorting
One Swap Sorting
One Swap Sorting
You are given an array of n integers. Your task is to determine if the array can be sorted in non-decreasing order by performing at most one swap between any two elements.
In other words, let the array be represented as \(a_1, a_2, \dots, a_n\) and its sorted version be \(b_1, b_2, \dots, b_n\). Identify all positions \(i\) where \(a_i \neq b_i\). The array is considered sortable with at most one swap if either:
- No positions differ, i.e. the array is already sorted, or
- Exactly two positions differ; swapping these two elements will result in a sorted array.
If the number of mismatched positions is any value other than 0 or 2, you should output No
.
Note: The input will contain multiple test cases. For each test case, output the result on a separate line.
inputFormat
The first line contains an integer T, the number of test cases.
For each test case:
- The first line contains an integer n, the number of elements in the array.
- The second line contains n space-separated integers representing the array elements.
outputFormat
For each test case, print a single line containing Yes
if the array can be sorted by at most one swap or No
otherwise.
1
5
1 2 3 4 5
Yes
</p>