Implementation of bubble sort in PHP

We need a nested loop to implement the bubble sort algorithm. The outer loop needs to continue iterating from the index 0 to n – 1( here, n is the number of items). The inner loop starts from the index 0 and continue iterating to the n – (i+1) ( here, i is the first loop index ).

$data_array = [10,5,2,8,7,3,6];

function bubble_sort( $data_array ){
	for( $i=0; $i < count( $data_array ) - 1; $i++ ){
		for( $j=0; $j < count( $data_array ) - ($i+1); $j++ ){
			if( $data_array[$j] > $data_array[$j+1] ){
				$temp = $data_array[$j+1];
				$data_array[$j+1] = $data_array[$j];
				$data_array[$j] = $temp;
			}
		}
	}
	return $data_array;
}

echo '<h1>Before Sort</h1>';
echo '<pre>';
print_r($data_array);
echo '</pre>';
echo "<br>";
echo '<h1>After Sort</h1>';
$sorted_items = bubble_sort( $data_array ); 
echo '<pre>';
print_r($sorted_items);
echo '</pre>';

Output:

Leave a Reply

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