Skip to content

Instantly share code, notes, and snippets.

@bytao7mao
Created August 11, 2017 04:19
Show Gist options
  • Save bytao7mao/b71a007b1aa7576025683a460823114f to your computer and use it in GitHub Desktop.
Save bytao7mao/b71a007b1aa7576025683a460823114f to your computer and use it in GitHub Desktop.
Bubble Sort
Bubble Sort
Suppose A is an array of N values. We want to sort A in ascending order.
Bubble Sort is a simple-minded algorithm based on the idea that we look at the list, and wherever we find two consecutive elements out of order, we swap them. We do this as follows: We repeatedly traverse the unsorted part of the array, comparing consecutive elements, and we interchange them when they are out of order. The name of the algorithm refers to the fact that the largest element "sinks" to the bottom and the smaller elements "float" to the top.
For I = 0 to N - 2
For J = 0 to N - 2
If (A(J) > A(J + 1)
Temp = A(J)
A(J) = A(J + 1)
A(J + 1) = Temp
End-If
End-For
End-For
Bubble Sort does roughly N**2 / 2 comparisons and does up to N**2 / 2 swaps.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment