algorithm-notes
  • Preface
  • Outline
    • Asymptotic-Analysis
    • Divide-and-Conquer (DnC)
      • Overview
      • Multiplication
      • DnC Strategy
      • Master Method
    • Randomization
      • Overview
      • Discrete Probability
      • Randomized Algorithms
      • Reservoir Sampling
    • Sorting
      • Overview
      • Selection Sort
      • Bubble Sort
      • Insertion Sort
      • Shell Sort
      • Merge Sort
      • Heap Sort
      • Quick Sort
      • Non-Comparison Sort
    • Graph Algorithms
      • Overview
      • Minimum Spanning Tree
      • Shortest Path
      • Topological Sort
    • Tree
      • Overview
      • Balanced Search Tree
        • AVL Tree
        • Red-Black Tree
        • B Tree
      • Heap
      • Disjoint Set
      • Threaded Binary Tree
      • Segment Tree
    • Searching
      • Overview
      • Binary Search
      • Graph Search
      • Hash Table
      • String Search
    • Dynamic Programming
      • Overview
      • Fibonacci Numbers
      • LCS problem
    • Greedy Algorithms
      • Overview
Powered by GitBook
On this page
  • Pseudocode
  • Algorithm Analysis

Was this helpful?

  1. Outline
  2. Sorting

Bubble Sort

PreviousSelection SortNextInsertion Sort

Last updated 6 years ago

Was this helpful?

is a simple yet straightforward swap sorting primitive and its principle is the same as what you might expect from a bubble surfacing up and down in the water.

Pseudocode

A naive implementation would be as follow to bubble up the biggest number to the rightmost position in each run for computing the ascending sequence and bubble up the smallest number to the rightmost position in each run for computing the descending sequence:

BUBBLE_SORT(array)
  for i := 1 to length(array)
    for j := 1 to length(array) - i
      if array[j] > array[j+1]
        swap(array[j], array[j+1])

To improve upon that, a sentinel is introduced so as to resolve useless iterations and comparisons in partially sorted inputs:

BUBBLE_SORT(array)
  sentinel := 1
  for i := 1 to length(array)
    if sentinel = 1
     break
    for j := 1 to length(array) - i
      if array[j] > array[j+1]
        swap(array[j], array[j+1])
        sentinel := 0

Algorithm Analysis

is elementary yet simple to evaluate; it yields a scenario of Ο(n) for partially sorted arrays and of Ο(n2)

Bubble Sort
best-case
worst-case
bubble sort