Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

finish exercise #46

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# assignment_sort
Insertion and Merge Sort assignment

Tingting Wang
16 changes: 16 additions & 0 deletions bubble.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require 'pry'

def bubble_sort(array)
last = array.length - 2

array.length.times do
(0..last).each do |index|
first = array[index]
second = array[index+1]
if first > second
array[index], array[index+1] = second, first
end
end
end
array
end
25 changes: 25 additions & 0 deletions insertion.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def insert(array, right_index, value)
# value is the value of array[right_index + 1]
# right_index is the furthest right sorted element

# Step through sorted elements right to left.
# As long as your value is less than the element
# at array[i] and you still have elements
i = right_index
while(i >= 0 && array[i] > value)
# copy the element
array[i+1] = array[i]
i -= 1
end

# insert the actual element
array[i+1] = value;
end

def insertion_sort(array)
array.each_with_index do |value, index|
right_index = index-1
insert(array, right_index, value)
end
array
end
31 changes: 31 additions & 0 deletions merge.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
def merge_sort(array)
return array if array.length <= 1

split = array.length / 2
left = array[0..split-1]
right = array[split..-1]

left_merge = merge_sort(left)
right_merge = merge_sort(right)

merge(left_merge, right_merge)

end

def merge(left_merge, right_merge)
sorted = []
until left_merge.empty? && right_merge.empty?
if left_merge.empty?
sorted += right_merge
right_merge = []
elsif right_merge.empty?
sorted += left_merge
left_merge = []
elsif left_merge[0] <= right_merge[0]
sorted << left_merge.shift
elsif right_merge[0] < left_merge[0]
sorted << right_merge.shift
end
end
sorted
end