Module: Functional::Sort

Extended by:
Sort
Included in:
Functional, Sort
Defined in:
lib/functional/sort.rb

Instance Method Summary collapse

Instance Method Details

#insertion_sort!(data, opts = {}) {|item| ... } ⇒ Array

Sorts the collection using the insertion sort algorithm.

When a block is given the block will be applied to both arguments. Using a block in this way allows computation against a specific field in a data set of hashes or objects.

Parameters:

  • data (Enumerable)

    the data set to search

  • opts (Hash) (defaults to: {})

    search options

Yields:

  • iterates over each element in the data set

Yield Parameters:

  • item

    each element in the data set

Returns:

  • (Array)

    the sorted collection



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/functional/sort.rb', line 19

def insertion_sort!(data, opts={})
  return data if data.nil? || data.size <= 1

  (1..(data.size-1)).each do |j|

    key = block_given? ? yield(data[j]) : data[j]
    value = data[j]
    i = j - 1
    current = block_given? ? yield(data[i]) : data[i]

    while i >= 0 && current > key
      data[i+1] = data[i]
      i = i - 1
      current = block_given? ? yield(data[i]) : data[i]
    end

    data[i+1] = value
  end

  return data
end