Bubble Sort
For an input sequence, adjacent elements are compared one by one. If the element on the left is greater than the element on the right, they are swapped. This process repeats until there are no more pairs of adjacent elements that need to be exchanged; at this point, the list's elements are sorted.
- Compare adjacent elements. If the first is larger than the second, swap them.
- Perform the same operation on every pair of adjacent elements from the beginning up to the last pair in the sequence. After completing this step, the final element will be the largest number.
- Repeat the above steps for all elements except the last one.
- Continue repeating the previous step on progressively fewer pairs until no two numbers need comparison.
Code Implementation
::: code-tabs
@tab Java
public class BubbleSort implements IArraySort {
@Override
public int[] sort(int[] sourceArray) throws Exception {
// Create a copy of arr to avoid modifying the original parameter content
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 1; i < arr.length; i++) {
// Set a flag: if true, it means no swap occurred in this loop iteration, indicating the sequence is already sorted.
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
}
@tab JavaScript
function bubbleSort(arr) {
var len = arr.length;
for (var i = 0; i < len - 1; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j+1]) { // Compare adjacent elements pairwise
var temp = arr[j+1]; // Swap elements
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
@tab Python
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
@tab Go
func bubbleSort(arr []int) []int {
length := len(arr)
for i := 0; i < length; i++ {
for j := 0; j < length-1-i; j++ {
if arr[j] > arr[j+1] {
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
return arr
}
@tab PHP
function bubbleSort($arr){
$len = count($arr);
for ($i = 0; $i < $len - 1; $i++) {
for ($j = 0; $j < $len - 1 - $i; $j++) {
if ($arr[$j] > $arr[$j+1]) {
$tmp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $tmp;
}
}
}
return $arr;
}
:::