So Bubble Sort is the most basic kind of swap Sort. The idea is to compare two neighboring elements in turn, swap them if they are in reverse order, and repeat the comparison until no neighboring elements need to be swapped.

Complexity analysis

  • Best case:O(n)
  • Worst case:O (n squared)
  • Average:O (n squared)

Java code implementation

import java.util.Arrays; public class BubbleSort { public static void sort(int[] data) { int temp = 0; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length - i - 1; j++) { if (data[j] > data[j + 1]) { temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; } } System.out.println(Arrays.toString(data)); } } public static void main(String[] args) { int[] data = {34, 24, 93, 1, 32, 98, 18, 39}; sort(data); }}Copy the code

The results

[24, 34, 1, 32, 93, 18, 39, 98] [1, 24, 32, 34, 18, 39, 93, 98] [1, 18, 24, 32, 34, 39, 93, 98] [1, 18, 24, 32, 34, 39, 93, 98] [1, 18, 24, 32, 34, 39, 93, 98] 34, 39, 93, 98]Copy the code