sorting - Algorithm to merge sorted arrays -


The exact description is:

The length of the array is n , made Key and value are both positive integers with key-value pairs and the key is unique in each array.

There are x arrays, and the keys to each array are not exactly the same.

Now I need to merge these x arrays by adding these key together with the same key and adding the value to n n + 1 and pair has the same value with the top n and pair, then ignore it.

If necessary, you can assume that each array is sorted by the key or value.

Eg n = 3 and x = 3 :

3 length 3 array: [(1,2 ), (2,3), (3,4)], [(2,3), (3,2), (4,1)], [(2,2), (5, 2), (6) , 2)]

merged: [(1,2), (2,8), (3,6), (4,1), (5,2) , (6,2)]

top 3: [(2,8), (3,6), (5,2)]

So what's the best algorithm to do this?

You merge a by-route with the key, and a priority queue - usually one more Miner-pile

Arrays are sorted by key, in ascending order. So you make a minimum pile and put the first object from each array on the heap. So you constantly remove the lowest item while adding the sum of the same objects. Since each item is removed from the merge pile, you add that item from the item that came from the item. The output goes to the minimum pile of K, where K is the number of items you want in the output.

The output compares the value compared to the heap key.

Quick pyodocode example:

  heapNode = struct {parray / reference reference of reference array index / start current array index starting 0 and increment each time} mergeHeap = new Minhweep OutputHope = New Minhepe for each array merge. Add (NewHeapnode (array, 0) Previous = -1 previous value = 0 while mergehap is not empty {node = mergeHeap.RemoveSmallest key = node.array [node.index] .key value = node.array [node.index] .value // Update the array index and node it back onto the hex index.node.index + 1 if (node.index and lt; node.array.length) mergeHeap.Add (node) // now collects the sum if (Key == of previous) {previous value + = value;} and {// new key} If one output output (previous of! = -1) {if outputHeap.Count & LT (Output for number output) Ed (new output node (backcode , The previous value) and if (previous value> OutputMap .PEC () value) {// Output already has less value than the output heap. }} Previously = key previousValue = value}} // Here you will see the previous and previous value // whether they want to see if they are now on your output pile // Now your output pile has the highest value items Are you Remove them while output empty empty node = output. Hide The lowest output node (node)   

This is the basic idea that just a heap is required.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -