What is Bubble Sort ?

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
Algorithm

  1. Loop through the whole array starting from index 1
  2. If the number in the array at index i-1 is greater than i, swap the numbers and continue
  3. Once the end of the array is reached, start looping again from the beginning
  4. Once no more elements can be swapped, the sorting is complete

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes

Implementation

Bubble sort works by going through the array multiple times and swapping elements that are out of order as we go through the array. Every pass through the array, we move the largest element to the end.

15,6,3,11,5. (Swap 15,6)
6,15,3,11,5. (Swap 15,3)
6,3,15,11,5. (Swap 15,11)
6,3,11,15,5. (Swap 15,5)
6,3,11,5,15. (Swap 6,3)
3,6,11,5,15. (Swap 11,5)
3,6,5,11,15. (Swap 6,5)
3,5,6,11,15.

Code 

// Display For Array
function display($number){
   $len = count($number); 
   $message = "<div>";  
   for($i=0;$i<$len;$i++){
      $message .= $number[$i];
      $message .= ($len==$i+1)? ".":",";
   }
   $message .= "</div>";
   return $message;
}
// Function of Buuble Sort
function bubbleSort($number){
   $len = count($number);
   for($i = $len - 1; $i >= 0; $i--) {
      for($j = 1; $j <= $i; $j++) {
         if($number[$j-1] > $number[$j]) {
            //Swap
            $temp_A = $number[$j-1];
            $temp_B = $number[$j];
            echo display_num($number,$temp_A,$temp_B);
            $number[$j] = $temp_A;
            $number[$j-1] = $temp_B;            
         }
      }
   }
   return $number;
}
// Array 
$array = [3, 203, 34, 746, 200, 984, 198, 764, 9];
echo " <p>Before Sorting </p>";
echo display($array); 
//3,203,34,746,200,984,198,764,9.
echo "<p> After Sorting </p>";
$sort_array = bubbleSort($array);
echo display($sort_array);
//3,9,34,198,200,203,746,764,984.

Live Demo

Bubble Sort

(Visited 273 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

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