I have an array of numbers sorted in ascending or descending order, and I want to find the index into which to insert the number while maintaining the order of the array. If the array is [1, 5, 7, 11, 51] and the insert number is 9 , I would expect 3 so that I can make [1, 5, 7, 11, 51].insert(3, 9) . If the array is [49, 32, 22, 11, 10, 8, 3, 2] and the number to be inserted is 9 , I would expect 5 so that I can do [49, 32, 22, 11, 10, 8, 3, 2].insert(5, 9)
What is the best / cleanest way to find the index where you need to insert 9 into either of these two arrays while maintaining the array sort?
I wrote this code that works, but it is not very pretty:
array = [55, 33, 10, 7, 1] num_to_insert = 9 index_to_insert = array[0..-2].each_with_index.map do |n, index| range = [n, array[index.next]].sort index.next if num_to_insert.between?(range[0], range[1]) end.compact.first index_to_insert