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
- Loop through the whole array starting from index 1
- If the number in the array at index i-1 is greater than i, swap the numbers and continue
- Once the end of the array is reached, start looping again from the beginning
- 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.
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