Created
August 11, 2017 04:19
-
-
Save bytao7mao/b71a007b1aa7576025683a460823114f to your computer and use it in GitHub Desktop.
Bubble Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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