add mergesort

This commit is contained in:
xxDOOMbox 2017-10-01 16:31:40 -04:00
parent 5cd15d08d8
commit 355f0c8dc8
5 changed files with 48 additions and 12 deletions

View file

@ -13,6 +13,6 @@ class Array
end end
end end
puts "Enter a list of numbers seprated by space" puts "Enter a list of numbers separated by spaces"
str = gets.chomp.split('') str = gets.chomp.split('')
puts str.bogosort.join('') puts str.bogosort.join('')

View file

@ -15,7 +15,7 @@ def bubble_sort(array)
array array
end end
puts "Enter a list of numbers seprated by space" puts "Enter a list of numbers separated by spaces"
list = gets list = gets
bubble_sort(list) bubble_sort(list)

View file

@ -10,7 +10,7 @@ def insertion_sort(array)
end end
array array
end end
puts "Enter a list of numbers seprated by space" puts "Enter a list of numbers separated by spaces"
list = gets list = gets
insertion_sort(list) insertion_sort(list)

25
MergeSort.rb Normal file
View file

@ -0,0 +1,25 @@
def mergesort(arr)
return arr if arr.length <= 1
m = arr.length / 2
l = mergesort(arr[0...m])
r = mergesort(arr[m...arr.length])
merge(l, r)
end
def merge(l, r)
aux = []
until l.empty? || r.empty?
if l.first < r.first
aux << l.shift
else
aux << r.shift
end
end
aux.concat(l).concat(r)
end
puts "Enter a list of numbers separated by spaces"
arr = gets.chomp.split.map(&:to_i)
puts "Sorted: #{mergesort(arr)}"

View file

@ -19,7 +19,15 @@ __Properties__
###### View the algorithm in [action][bubble-toptal] ###### View the algorithm in [action][bubble-toptal]
### Merge Sort
![alt text][mergesort-image]
From [Wikipedia][mergesort-wiki]:
Conceptually, a merge sort works as follows:
1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
2. Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
### Insertion Sort ### Insertion Sort
![alt text][insertion-image] ![alt text][insertion-image]
@ -59,3 +67,6 @@ __Properties__
[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort [insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort
[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort [insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort
[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" [insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort"
[mergesort-wiki]: https://en.wikipedia.org/wiki/Merge_sort
[mergesort-image]: https://upload.wikimedia.org/wikipedia/commons/c/c5/Merge_sort_animation2.gif "Merge Sort"