I am trying to write a function that will check if it is possible to sort an array with a single swap of 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.
I tried the following code below, but I am stuck in it:
$noOfIterations = 0;
for($x = 0; $x < count($a)-2; $x++) {
if($a[$x] > $a[$x+1]) {
$noOfIterations ++;
}
}
return $noOfIterations >1;
$arr = [1, 3, 5, 3, 4];
$sortedArr = $arr;
sort($sortedArr);
print_r(array_intersect_assoc($arr,$sortedArr));
source
share