Sort array without using any built in function in php

Sort array without using any built in function in php

Posted by

Sometimes in a PHP interview, you may come across the task to sort an array in PHP without using any in-built or PHP core functions like sort(), rsort(), asort(), ksort(), arsort(), etc. You can apply the below steps for sorting an array:

Here is code to sort arrays in ascending order without a built-in function:

  1. Take an array: $arr = array(2,5,1,7,4)
  2. Initialize a loop from 0 to less than total count: for($i = 0; $i < count($arr); $i++ )
  3. Take second loop and it will run less than 2 of total count: for($j = 0; $j < count($arr)-1; $j++)
  4. Compare value from next: if($arr[$j+1] < $arr[$j])
  5. Initialize “$temp” variable and assign value if next one is small: $temp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $temp;
  6. Step 4 will run till the end of the loop.

Here is the code to sort arrays in descending order in PHP:

  1. follow the all above steps. Only you have to change in 4 step which is compare sign(>): if($arr[$j+1] > $arr[$j])

 

Leave a Reply

Your email address will not be published. Required fields are marked *