Skip to content

Instantly share code, notes, and snippets.

@cloudnull
Created March 13, 2014 20:42
Show Gist options
  • Save cloudnull/c1a9c0c87eca2542d435 to your computer and use it in GitHub Desktop.
Save cloudnull/c1a9c0c87eca2542d435 to your computer and use it in GitHub Desktop.
sort a list of integers
def linear_search(collection, low, high):
"""Returns a list of integers.
Search through a collection for all integers in a range.
>>> # sorted was add as the search should be a sorted list.
>>> Input = sorted([21, 23, 25, 28, 35, 45])
>>> linear_search(collection=Input, low=24, high=36)
:param collection: ``list``
:param low: ``int``
:param high: ``int``
"""
return sorted([x for x in collection if x in range(low, high)])
def left_linear_search(collection, low, high):
"""Returns a list of integers.
Search through a collection for all integers in a range.
>>> # sorted was add as the search should be a sorted list.
>>> Input = sorted([21, 23, 25, 28, 35, 45])
>>> left_linear_search(collection=Input, low=24, high=36)
:param collection: ``list``
:param low: ``int``
:param high: ``int``
"""
return_list = []
for n in collection:
if low <= n <= high:
return_list.append(n)
elif n > high:
break
return sorted(return_list)
def binary_search(collection, item):
"""Returns a list of integers.
Search through a collection for all integers in a range.
>>> # sorted was add as the search should be a sorted list.
>>> Input = sorted([21, 23, 25, 28, 35, 45])
>>> [x for x in range(24, 36) if binary_search(Input, x)]
:param collection: ``list``
:param item: ``object``
"""
bottom = 0
top = len(collection) - 1
while bottom <= top:
middle = (bottom + top) / 2
if collection[middle] == item:
return item
elif collection[middle] < item:
bottom = middle + 1
else:
top = middle - 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment