Bubble Sort
Bubble Sort
j<5
Num of
inter loop
j<bilNombor – 1 – 1
j<4
decrease
in every
outer loop
j<bilNombor – 2 – 1
j<3
Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
pair of adjacent items, and swaps them if they are in the wrong order. The process is repeated until the list is
sorted.
Example
unsorted list: [5, 2, 9, 1, 5, 6]
First Pass:
Compare 5 and 2, swap because 5 > 2: [2, 5, 9, 1, 5, 6]
Compare 5 and 9, no swap needed: [2, 5, 9, 1, 5, 6]
Compare 9 and 1, swap because 9 > 1: [2, 5, 1, 9, 5, 6]
Compare 9 and 5, swap because 9 > 5: [2, 5, 1, 5, 9, 6]
Compare 9 and 6, swap because 9 > 6: [2, 5, 1, 5, 6, 9]
End of first pass: the largest element (9) is in its final position.
Second Pass:
Compare 2 and 5, no swap needed: [2, 5, 1, 5, 6, 9]
Compare 5 and 1, swap because 5 > 1: [2, 1, 5, 5, 6, 9]
Compare 5 and 5, no swap needed: [2, 1, 5, 5, 6, 9]
Compare 5 and 6, no swap needed: [2, 1, 5, 5, 6, 9]
End of second pass: the second largest element (6) is in its final position.
Subsequent Passes: Continue the same process until the entire list is sorted: [1, 2, 5, 5, 6, 9]
Pyhton
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
temp=arr[j]
arr[j]=arr[j+1]
arr[j+1]=temp
swapped = True
if not swapped:
break
return arr
# Example usage
arr = [5, 2, 9, 1, 5, 6]
sorted_arr = bubble_sort(arr)
print(sorted_arr)
Java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 5, 6};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
JavaScript
function bubbleSort(arr) {
let n = arr.length;
let swapped;
for (let i = 0; i < n; i++) {
swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}
// Example usage
let arr = [5, 2, 9, 1, 5, 6];
console.log(bubbleSort(arr));
PHP
<?php
function bubbleSort(&$arr) {
$n = count($arr);
for ($i = 0; $i < $n; $i++) {
$swapped = false;
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
$swapped = true;
}
}
if (!$swapped) break;
}
}
$arr = [5, 2, 9, 1, 5, 6];
bubbleSort($arr);
print_r($arr);
?>