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'


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -