Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to insert an element into sorted array and find its index

I need to insert an element into sorted range, but I also need to know its index (number of elements in range that are less then the element). I want to do this in O(logN) time. Can I do this with basic C++ containers?

I was thinking to use std::multimap, with this container I can insert the element into its place with O(logN) complexity. But to get the index, I need to call std::distance, which takes O(N) operations, since multimap iterator is not random access.

Another way is to use sorted std::vector and std::binary_search algorithm. In this case the search takes O(logN), but the insertion will take O(N) operations, since the insertion to the middle of vector is linear operation.

So, is there std/boost container that I can use to reach the result, or I need to implement my own struct for this? Thanks!

like image 929
ALEXANDER KONSTANTINOV Avatar asked Feb 25 '16 21:02

ALEXANDER KONSTANTINOV


People also ask

Which one is an efficient way to search through a sorted array?

If we know nothing about the distribution of key values, then we have just proved that binary search is the best algorithm available for searching a sorted array.

What is the best case efficiency for insertion sort?

The best-case time complexity of insertion sort algorithm is O(n) time complexity. Meaning that the time taken to sort a list is proportional to the number of elements in the list; this is the case when the list is already in the correct order.

Which search is preferred when the array elements are sorted?

Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array.

Which search is most suitable if the elements are in sorted order?

Binary search works on sorted arrays.


1 Answers

You can use Boost.MultiIndex's ranked indices:

Live Coliru Demo

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/identity.hpp>

using namespace boost::multi_index;
using ranked_int_set=multi_index_container<
  int,
  indexed_by<
    ranked_unique<identity<int>>
  >
>;

#include <iostream>

int main()
{
  ranked_int_set s={0,2,4,6,8,10,12,14,16};

  auto it=s.insert(9).first;
  std::cout<<"9 was inserted at position #"<<s.rank(it)<<"\n";
  std::cout<<"14 is located at position #"<<s.find_rank(14)<<"\n";
}

Output

9 was inserted at position #5
14 is located at position #8
like image 164
Joaquín M López Muñoz Avatar answered Sep 20 '22 13:09

Joaquín M López Muñoz