mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-02-04 08:46:13 +01:00
Merge pull request #190 from ryanneilparker/master
Add binary insertion sort algorithm
This commit is contained in:
commit
3fec7ec3ae
2 changed files with 57 additions and 0 deletions
46
sorting/binary_insertion_sort.rb
Normal file
46
sorting/binary_insertion_sort.rb
Normal file
|
@ -0,0 +1,46 @@
|
|||
# Ruby implementation of binary insertion sort algorithm
|
||||
|
||||
def binary_search(arr, val, start, stop)
|
||||
while start <= stop
|
||||
|
||||
mid = (start + stop) / 2
|
||||
|
||||
if val == arr[mid] # val is in the middle
|
||||
return mid
|
||||
elsif val > arr[mid] # val is on the right side
|
||||
start = mid + 1
|
||||
else
|
||||
stop = mid - 1 # val is on the left side
|
||||
end
|
||||
end
|
||||
|
||||
start
|
||||
end
|
||||
|
||||
def binary_insertion_sort(arr)
|
||||
n = arr.size
|
||||
|
||||
(0...n).each do |index|
|
||||
j = index - 1
|
||||
selected = arr[index]
|
||||
|
||||
# find location where selected value should be inserted
|
||||
location = binary_search(arr, selected, 0, j)
|
||||
|
||||
# move all elements after location to make space
|
||||
while j >= location
|
||||
arr[j + 1] = arr[j]
|
||||
j -= 1
|
||||
arr[j + 1] = selected
|
||||
end
|
||||
end
|
||||
|
||||
arr
|
||||
end
|
||||
|
||||
if $0 == __FILE__
|
||||
puts 'Enter a list of numbers separated by space'
|
||||
|
||||
list = gets.split.map(&:to_i)
|
||||
p binary_insertion_sort(list)
|
||||
end
|
11
sorting/binary_insertion_sort_test.rb
Normal file
11
sorting/binary_insertion_sort_test.rb
Normal file
|
@ -0,0 +1,11 @@
|
|||
require 'minitest/autorun'
|
||||
require_relative './sort_tests'
|
||||
require_relative './binary_insertion_sort'
|
||||
|
||||
class TestBinaryInsertionSort < Minitest::Test
|
||||
include SortTests
|
||||
|
||||
def sort(input)
|
||||
binary_insertion_sort(input)
|
||||
end
|
||||
end
|
Loading…
Add table
Reference in a new issue