Skip to content

Instantly share code, notes, and snippets.

@senvey
Last active August 29, 2015 14:06
Show Gist options
  • Save senvey/6918e70557288aba60f6 to your computer and use it in GitHub Desktop.
Save senvey/6918e70557288aba60f6 to your computer and use it in GitHub Desktop.
Find the count of given number in a sorted array.
def count(array, n):
# starting point
left, right = 0, len(array)
while left < right:
mid = (left + right) / 2
if array[mid] >= n:
right = mid
else:
left = mid + 1
# before exiting the loop, right points
# to the given number if any:
# array[right] >= n
start = right
# ending point
left, right = 0, len(array)
while left < right:
mid = (left + right) / 2
if array[mid] <= n:
left = mid + 1
else:
right = mid
# before exiting the loop, left points
# to the immediate right of given number
# if any: array[left - 1] <= n
end = left
return end - start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment