I was looking at one of the questions How to merge two sorted arrays, and trying hard to convert the solution using Java 8 streams. But still no success. Actually, nothing useful that I can share here.
There has to be a way to handle such loops using indexes in functional programming. How would this been done in other languages, like Scala, Clojure, without changing the time complexity? May be then I can just try to copy it in Java.
Edit: The code mentioned the question is the most efficient, and I don't want to compromise on it.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
concat(array1, array2) to merge 2 or more arrays. These approaches are immutable because the merge result is stored in a new array. If you'd like to perform a mutable merge, i.e. merge into an array without creating a new one, then you can use array1.
The Array. concat() is an inbuilt TypeScript function which is used to merge two or more arrays together. Parameter: This method accepts a single parameter multiple time as mentioned above and described below: valueN : These parameters are arrays and/or values to concatenate.
in fact there is the same approach everywhere: you recur over two collections, adding least of collections' heads to the result, and recurring with the rest, until one of collections (or both) is empty. In clojure:
(defn merge-sorted [pred coll1 coll2]
(loop [coll1 coll1 coll2 coll2 res []]
(cond (or (empty? coll1) (empty? coll2)) (concat res coll1 coll2)
(pred (first coll1) (first coll2)) (recur (rest coll1)
coll2
(conj res (first coll1)))
:else (recur coll1 (rest coll2) (conj res (first coll2))))))
user> (merge-sorted < [1 3 5 6 7 8 9 40 50] [1 2 5 10 100])
(1 1 2 3 5 5 6 7 8 9 10 40 50 100)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With