0

I have a sorted Array and I would like to insert a new element in logarithmic time.

I want to do something like this:

def addElem(Array[Int] data, Int x) {
            val pos = java.util.Arrays.binarySearch(data,x);
            data.insertAfter(pos, x);
}

Can I do this with an Array?

Should I try a different data structure?

2
  • 3
    How could insertion to an array be log(N) when it needs O(n) to move part of array to make space for new element? Commented Dec 23, 2015 at 12:52
  • Does your sorted collection need to be able to handle duplicate elements? Commented Dec 23, 2015 at 14:05

1 Answer 1

2

Please consider scala collections performance charasteristics:

http://docs.scala-lang.org/overviews/collections/performance-characteristics.html

There are two types of collections that provide Log complexity for insert operation. They are: TreeSet, TreeMap (mutable and immutable).

I would suggest use them.

Regarding Arrays.binarySearch usage. It will not work as most likely you array will not contains x element, so it returns -1. Definitely you can implement binarySearch on Array[Int] by yourself that satisfy your needs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.