Class: Sorting::InsertionSort
- Inherits:
-
Object
- Object
- Sorting::InsertionSort
- Extended by:
- Helper
- Defined in:
- lib/sorting/insertion_sort.rb,
ext/sorting/sorting_ext.c
Constant Summary collapse
- TEST_DATA_SIZE =
1000- BINARY_SEARCH_THRESHOLD =
80- BINARY_SEARCH_TEST_DISTANCE =
[5, BINARY_SEARCH_THRESHOLD].min
- IS_EXT =
Qtrue
Class Method Summary collapse
- .binary_sort!(data, l = 0, r = data.size-1, start = l+1) ⇒ Object
-
.sort!(data, l = 0, r = data.size-1, start = l+1) ⇒ Object
Insertion sort Comparison sort Insertion Stable Time complexity: Ω(n), Ө(n2), O(n2) Space complexity: O(n) total, O(1) auxiliary Simple, Adaptive, Online More efficient in practice than bubble sort or selection sort Write O(n2) times.
Methods included from Helper
Class Method Details
.binary_sort!(data, l = 0, r = data.size-1, start = l+1) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/sorting/insertion_sort.rb', line 31 def self.binary_sort!(data, l=0, r=data.size-1, start=l+1) (start..r).each do |i| value = data[i] if (distance = i - l) > BINARY_SEARCH_THRESHOLD && value < data[i-BINARY_SEARCH_TEST_DISTANCE] low = l high = i-1 found = nil while low <= high mid = low + (high-low)/2 if data[mid] < value low = mid + 1 else found = mid high = mid - 1 end end if found length = i-found data[found+1, length] = data[found,length] data[found] = value end else j = i while j > l && value < (previous = data[j-1]) data[j] = previous j -= 1 end data[j] = value end end nil end |
.sort!(data, l = 0, r = data.size-1, start = l+1) ⇒ Object
Insertion sort Comparison sort Insertion Stable Time complexity: Ω(n), Ө(n2), O(n2) Space complexity: O(n) total, O(1) auxiliary Simple, Adaptive, Online More efficient in practice than bubble sort or selection sort Write O(n2) times
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/sorting/insertion_sort.rb', line 18 def self.sort!(data, l=0, r=data.size-1, start=l+1) (start..r).each do |i| value = data[i] j = i while j > l && value < (previous = data[j-1]) data[j] = previous j -= 1 end data[j] = value end nil end |