Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
(Added "long-hand") |
|||
Line 101: | Line 101: | ||
==[[Ruby]]== |
==[[Ruby]]== |
||
Sorting can be done with the sort method |
|||
new_array = [3, 78, 4, 23, 6, 8, 6].sort |
new_array = [3, 78, 4, 23, 6, 8, 6].sort |
||
#=> [3, 4, 6, 6, 8, 23, 78] |
#=> [3, 4, 6, 6, 8, 23, 78] |
||
# Sort on arbitrary criteria: |
# Sort on arbitrary criteria: |
||
new_array = [3, 78, 4, 23, 6, 8, 6].sort {|a,b| a % 2 <=> b} |
new_array = [3, 78, 4, 23, 6, 8, 6].sort {|a,b| a % 2 <=> b} |
||
#=> [3, 78, 8, 4, 6, 23, 6] |
#=> [3, 78, 8, 4, 6, 23, 6] |
||
This sort is actually a C quicksort. |
|||
Bubble sort algorithm |
|||
# Sort in place: |
|||
a = [3, 78, 4, 23, 6, 8, 6] |
|||
a.sort! |
|||
a |
|||
#=> [3, 4, 6, 6, 8, 23, 78] |