Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
(→‎[[Perl]]: removed note, everything has sort built-in)
(→‎[[Ruby]]: removed off-topic example)
Line 203: Line 203:
==[[Ruby]]==
==[[Ruby]]==
[[Category:Ruby]]
[[Category:Ruby]]
Sorting can be done with the sort method
new_array = [3, 78, 4, 23, 6, 8, 6].sort
#=> [3, 4, 6, 6, 8, 23, 78]
# Sort on arbitrary criteria:
new_array = [3, 78, 4, 23, 6, 8, 6].sort {|a,b| a % 2 <=> b}
#=> [3, 78, 8, 4, 6, 23, 6]
# Sort and modify the current object to be sorted
ary = [3, 78, 4, 23, 6, 8, 6]
ary.sort! {|a,b| a % 2 <=> b}
#ary => [3, 78, 8, 4, 6, 23, 6]
This sort is actually a C quicksort.

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.
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.