Bubble sort

Bubble sort algorithm is the most famous sorting algorithm as it is studied in schools, universities and various computer courses.

The idea of the algorithm is as follows:

  • we iterate through the array and swap adjacent elements pair by pair if they aren’t in the required order.
  • each iteration through the array pushes one item (“bubble”) to the outermost position.

The main weak point of this approach: the time complexity is O(n2).

This algorithm is created for educational purposes only: never use it in production code!

import java.util.Arrays;

public class ImplementBubbleSort {

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

  public static void main(String[] args)
  {
    var array = new int[] { 64, 34, 25, 12, 22, 11, 90 };
    var n = array.length;
    bubbleSort(array, n);
    System.out.println("Sorted array: ");
    System.out.println(Arrays.toString(array));
  }
}

1 thought on “Bubble sort”

  1. Pingback: Insertion sort – Mike Scherbakov

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top