php - Check if the array can be sorted with a single swap of 2 elements -
i trying write function check if array can sorted single swap of values in array.
for example: array(1,3,5,3,7)
must return true
, array(1,3,5,3,4)
must return false
.
i tried following code below, i'm stuck it:
$noofiterations = 0; for($x = 0; $x < count($a)-2; $x++) { if($a[$x] > $a[$x+1]) { $noofiterations ++; } } return $noofiterations >1; // below solution helped well. //$arr = [1, 3, 5, 3, 7]; //[1, 3, 5, 3, 4] $arr = [1, 3, 5, 3, 4]; $sortedarr = $arr; sort($sortedarr); print_r(array_intersect_assoc($arr,$sortedarr));
execute sort, compare original array sorted array using array_intersect_assoc().... if difference more 2 elements, answer 'no'