Bubble Sort

Sopheary Rin (Sofia)
2 min readJan 19, 2024

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

How does it work?

We have an array : 5, 1, 4, 2, 8 and we want to sorted it in increasing order, it will be: 1,2,4,5,8.

  • traverse from left and compare adjacent elements and the higher one is placed at right side.
  • In this way, the largest element is moved to the rightmost end at first.
  • This process is then continued to find the second largest and place it and so on until the data is sorted.

Coding in Java:

// An optimized version of Bubble Sort
static void bubbleSort(int arr[], int n)
{
int i, j, temp;
boolean swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

// If no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}

Resources: https://www.geeksforgeeks.org/bubble-sort/

--

--