PHP: bubble sort implementation

Bubble sort, as the name suggests, it bubbles up the element to the correct position each time it loops through the element list. For example, to sort the list in ascending order and the loop starts from index 0. The first loop will move the largest element to the end of the list, second loop will move the largest element in the remaining list to the second position of the end of the list. Before going through the loop, we will check a boolean variable(isSwapped), and starts the loop only if it is true. The first line of the loop will set isSwapped to false, it will be marked to true if there is a swap between elements. If there is no swaps, then the list is sorted. There will be a outer while loop checks if isSwapped is true, if it is true, then starts the inner loop to swap adjacent elements as needed. It compares A(index 0) and B(index 1), if A is greater than B, swap them. Then compares A(now index 1) and C(index 2), if A is greater than C, swap. Then compares A(now index 2) and D(index 3), if A is greater than D, swap, assume this time it is not greater than D, no swaps. Then compares D(index 3) and E(index 4), if D is greater than E, swap. Keep doing this until the end of unsorted elements.
Here is an example of bubble sort in PHP

<?php
function bubbleSort($data)
{
	$swapped=true;
	$n=count($data);
	$temp=null;
	while($swapped)//outer loop
	{
		$swapped = false;
		for($i=0; $i<$n-1; $i++)//inner loop
		{
			if( $data[$i]>$data[$i+1]) //swap if the current value is greater the next value. change > to > for descending order
			{
				$temp=$data[$i];
				$data[$i]=$data[$i+1];
				$data[$i+1]=$temp;
				$swapped=true;
			}
		}
	}

	return $data;
}

echo implode(",",array(43,23,4,11,2,88,76,46));
echo "<br>";
echo implode(",",bubbleSort(array(43,23,4,11,2,88,76,46)));

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search