Sort Algorithm - Bubble Sort

Last updated on September 4, 2023 pm

Definition:

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. It continues these steps until the entire list is sorted. While straightforward, it’s not very efficient for large lists due to its O(n^2) time complexity.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 9, -1, 10, 2};

bubbleSort(arr);
}

public static void bubbleSort(int[] arr) {

// Initialize a flag to track if any swaps were made
boolean flag = false;

// Temporary variable for swapping elements
int temp = 0;

// Loop through the array
for (int i = 0; i < arr.length; i++) {
// Iterate through the array up to the unsorted portion
for (int j = 0; j < arr.length - 1 - i; j++) {
// Compare adjacent elements and swap if they are out of order
if (arr[j] > arr[j + 1]) {
flag = true; // Set the flag to indicate a swap
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

// If no swaps were made in this pass, the array is already sorted
if (!flag) {
break;
} else {
flag = false; // Reset the flag for the next pass
}
}

// Print the sorted array
System.out.println(Arrays.toString(arr));

}
}

Sort Algorithm - Bubble Sort
http://hihiko.zxy/2023/09/04/Sort-Algorithm-Bubble-Sort/
Author
Posted on
September 4, 2023
Licensed under