Bubble Sort
Bubble Sort :
Author(s) : Unknown Date : AncientBubble sort is a simple sorting algorithm that iterates repeatedly through the input array. In each pass, it compares adjacent elements and swaps them if they are in the wrong order (larger element comes before the smaller one). This process is akin to bubbles of larger elements gradually rising to the end of the array. While conceptually straightforward, bubble sort has a time complexity of O(n²) in the worst case, making it inefficient for large datasets.
Time Complexity | O(n²) |
Best Case | O(n) |
Worst Case | O(n²) |
Space Complexity | O(1) |
Stable | Yes |
Code Integration:
* the code might contain some bugs or may not work correctly
def bubblesort(arr):
n = len(arr)
# Flag to track if any swaps occurred
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i] # swap
swapped = True
# Test array
arr = [64, 34, 25, 12, 22, 11, 90]
bubblesort(arr)
print('Sorted array is:', arr)
function bubblesort(arr) {
let n = arr.length;
// Flag to track if any swaps occurred
let swapped = true;
while (swapped) {
swapped = false;
for (let i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap using destructuring
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
}
}
// Test array
let arr = [64, 34, 25, 12, 22, 11, 90];
bubblesort(arr);
console.log('Sorted array is:', arr);
public static void bubblesort(int[] arr) {
int n = arr.length;
// Flag to track if any swaps occurred
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap elements
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}
// Test array
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bublesort(arr);
System.out.println("Sorted array is:" + java.util.Arrays.toString(arr));
}
func bubblesort(arr []int) {
n := len(arr)
// Flag to track if any swaps occurred
swapped := true
for swapped {
swapped = false
for i := 0; i < n-1; i++ {
if arr[i] > arr[i+1] {
// Swap elements
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}
}
// Test array
arr := []int{64, 34, 25, 12, 22, 11, 90}
bubblesort(arr)
fmt.Println("Sorted array is:", arr)
}
void bubblesort(int arr[], int n) {
// Flag to track if any swaps occurred
int swapped = 1;
while (swapped) {
swapped = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap elements
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
}
// Test array
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubblesort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}