Bubble sort is a sorting algorithm. This sorting algorithm is comparison based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

function bubbleSort($arr) {
    $len = count($arr);
    for ($i=0; $i<$len; $i++) {
      for ($j=0; $j<$len-1; $j++) {
          if ($arr[$j] > $arr[$j+1]) {
            $tmp = $arr[$j+1];
            $arr[$j+1] = $arr[$j];
            $arr[$j] = $tmp;
          }
      }
    }
    return $arr;
}

$arr = [10, 20, 5, 11, 6, 25, 1, 9, 21];
print_r(bubbleSort($arr));

Last Modified: 2 years ago