Sorting algorithms/Bubble sort: Difference between revisions

m
Spelling/grammar/aesthetics.
m (→‎{{header|Perl}}: Add link.)
m (Spelling/grammar/aesthetics.)
Line 6:
=Algorithm=
 
The '''bubble sort''' is generally considered to be the simplest sorting algorithm. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n<sup>2</sup>) performance, it is never used anywhere else.
 
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions. Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. (Large values "bubble" rapidly toward the end, pushing others down around them.) A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
 
This can be expressed in pseudocode as follows (assuming 1-based indexing):
Line 211:
| e1 > e2 = sweep (i + 1) False {array & [i - 1] = e2, [i] = e1}
= sweep (i + 1) done array
Using it to sort an array of a hunderdhundred numbers:
Start :: {Int}
Start = bsort {x \\ x <- [100,99..1]}
Line 234:
 
=={{header|Forth}}==
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity.
 
defer bubble-test
Line 289:
| otherwise = x:(_bsort (x2:xs))
_bsort s = s
This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one.
bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
Line 303:
 
=={{header|Java}}==
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type:
for(int a = 0; a < comparable.length - 1; a++){
for(int b = a + 1; b < comparable.length; b++){
Line 441:
 
=={{header|Ruby}}==
Although the native Ruby sort method for Arrays if much faster (O(n*log(n)) versus O(n**2)), you can find a Ruby version of Bubble sort hereunder. It adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby.
 
class Array
Anonymous user