php sort algorithm of bubble sort quick sort

  • 2020-05-26 08:03:10
  • OfStack

Bubble sort implementation principle

First put the number to be sorted into the work list.
From the list of the first number to the last two Numbers, check one by one: if the number of a bit is greater than his next bit, it will be swapped with its next bit.

Repeat the steps until they can no longer be exchanged.

Code implementation


<?php
 function bubbingSort(array $array)
 {
     for($i=0, $len=count($array)-1; $i<$len; ++$i)
     {
         for($j=$len; $j>$i; --$j)
         {
             if($array[$j] < $array[$j-1])
             {
                 $temp = $array[$j];
                 $array[$j] = $array[$j-1];
                 $array[$j-1] = $temp;
             }
         }
     }
     return $array;
 }

 print '<pre>';
 print_r(bubbingSort(array(1,4,22,5,7,6,9)));
 print '</pre>';

Quicksort implementation principle
Divide and conquer: make sure that the first half of the list is smaller than the second half, and then sort the first half and the second half separately, so that the whole list is in order.

Code implementation


function quickSort(array $array)
 {
     $len = count($array);
     if($len <= 1)
     {
         return $array;
     }
     $key = $array[0];
     $left = array();
     $right = array();
     for($i=1; $i<$len; ++$i)
     {
         if($array[$i] < $key)
         {
             $left[] = $array[$i];
         }
         else
         {
             $right[] = $array[$i];
         }
     }
     $left = quickSort($left);
     $right = quickSort($right);
     return array_merge($left, array($key), $right);
 }

 print '<pre>';
 print_r(quickSort(array(1,4,22,5,7,6,9)));
 print '</pre>';


Related articles: