Method: Algorithms::Sort.shell_sort
- Defined in:
- lib/algorithms/sort.rb
.shell_sort(container) ⇒ Object
Shell sort: Similar approach as insertion sort but slightly better. Requirements: Needs to be able to compare elements with <=>, and the [] []= methods should be implemented for the container. Time Complexity: О(n^2) Space Complexity: О(n) total, O(1) auxiliary Stable: Yes
Algorithms::Sort.shell_sort [5, 4, 3, 1, 2] => [1, 2, 3, 4, 5]
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/algorithms/sort.rb', line 122 def self.shell_sort(container) increment = container.size/2 while increment > 0 do (increment..container.size-1).each do |i| temp = container[i] j = i while j >= increment && container[j - increment] > temp do container[j] = container[j-increment] j -= increment end container[j] = temp end increment = (increment == 2 ? 1 : (increment / 2.2).round) end container end |