diff --git a/README.md b/README.md index dc1a8aa..5fa420d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,22 @@ -# assignment_sort -Insertion and Merge Sort assignment +# Implementing searching algorithms + +* bubble_sort.rb - implementation of bubble sort algorithm with an array +* insertion_sort.rb - implementation of insertion sort algorithm with an array +* merge_sort.rb - implementation of merge sort algorithm with an array + +## Getting Started + +If you want to quick run some the examples to see the code in action, run +``` +$ ruby example.rb +``` +from the project directory. + +## Authors + +* **Dariusz Biskupski** - *Initial work* - https://dariuszbiskupski.com + + +## Acknowledgments + +It is part of the assignment created for [Viking Code School](https://www.vikingcodeschool.com/) diff --git a/bubble_sort.rb b/bubble_sort.rb new file mode 100644 index 0000000..cbb10fa --- /dev/null +++ b/bubble_sort.rb @@ -0,0 +1,14 @@ +def bubble_sort(array) + temp_value = 0 + while temp_value != nil + temp_value = nil + (array.length - 1).times do |idx| + if array[idx] > array[idx + 1] + array[idx], array[idx + 1] = array[idx + 1], array[idx] + end + end + end + puts "#{array}" +end + +bubble_sort( [1,3,7,2,5] ) diff --git a/insertion_sort.rb b/insertion_sort.rb new file mode 100644 index 0000000..48e93d6 --- /dev/null +++ b/insertion_sort.rb @@ -0,0 +1,20 @@ + +def insert(array, right_index, value) + i = right_index + while(i >= 0 && array[i] > value) + array[i+1] = array[i] + i -= 1 + end + array[i+1] = value +end + + +def insertion_sort(array) + 1.upto(array.length - 1) do |idx| + element = array[idx] + insert(array, idx - 1, element) + end + puts "#{array}" +end + +insertion_sort( [1,3,7,2,5] ) diff --git a/merge_sort.rb b/merge_sort.rb new file mode 100644 index 0000000..383b518 --- /dev/null +++ b/merge_sort.rb @@ -0,0 +1,39 @@ + +def merge(left_arr, right_arr) + new_arr = [] + unless left_arr.nil? || right_arr.nil? + while left_arr.any? || right_arr.any? + if left_arr.empty? + new_arr << right_arr[0] + right_arr = right_arr[1..-1] + elsif right_arr.empty? + new_arr << left_arr[0] + left_arr = left_arr[1..-1] + elsif left_arr[0] > right_arr[0] + new_arr << right_arr[0] + right_arr = right_arr[1..-1] + else + new_arr << left_arr[0] + left_arr = left_arr[1..-1] + end + end + end + new_arr +end + +def merge_sort(array) + if array.length == 1 + array + else + left_arr = array[0...array.length/2] + right_arr = array[array.length/2..-1] + # // mergeSort() the left half of the array + # merge_sort(left_arr) + # // mergeSort() the right half of the array + # merge_sort(right_arr) + # // merge() the two halves + merge(merge_sort(left_arr), merge_sort(right_arr)) + end +end + +merge_sort( [1,3,7,2,5,4,30,22,80,50,6] )