Module: Searchractor::InstanceMethods

Defined in:
lib/searchractor.rb

Overview

Internal: Searchractor’s instance methods

Instance Method Summary collapse

Instance Method Details

#b_search(element) ⇒ Object

Public: Use binary search to look for an element in an initialized list of sorted elements.

Examples

searchable = SearchractorClass.new([1, 2, 3, 5, 8])

searchable.b_search(5) => 3

searchable.b_search(10) => nil

Returns either the index of the searched element or nil if the element is not found

in the sorted list


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/searchractor.rb', line 36

def b_search(element)
  i = 0
  j = list.length - 1

  while i <= j
    middle = (i + j) / 2

    return middle if element == list[middle]

    if element < list[middle]
      j = middle - 1
    else
      i = middle + 1
    end
  end
end

#l_search(element) ⇒ Object

Public: Use linear search to look for an element in an initialized list of elements.

Examples:

searchable = SearchractorClass.new([1, 4, 3, 8, 6])

searchable.l_search(3) => 2

searchable.l_search(10) => nil

Returns either the index of the searched element or nil if the element is not found

in the list


65
66
67
68
69
70
71
72
73
# File 'lib/searchractor.rb', line 65

def l_search(element)
  i = 0

  while i <= list.length - 1
    i += 1

    return i if element == list[i]
  end
end