Skip to content

Instantly share code, notes, and snippets.

@dmeremyanin
Created August 16, 2012 14:22
Show Gist options
  • Save dmeremyanin/3370468 to your computer and use it in GitHub Desktop.
Save dmeremyanin/3370468 to your computer and use it in GitHub Desktop.
Insert a number into a sorted array
class Array
def sorted_insert!(value)
min, max = 0, size
while max > min
middle = (min + max) / 2
if self[ middle ] > value
max = middle
else
min = middle + 1
end
end
insert(max, value)
end
def sorted_insert(value)
dup.sorted_insert!(value)
end
end
@dmeremyanin
Copy link
Author

(0..1_000_000).to_a.sorted_insert(800_000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment