Optimal bubble sorting algorithm for an array of arrays of numbers

前端 未结 3 1747
不知归路
不知归路 2021-02-01 03:59

Fix positive integers n and k.

Let A be an array of length n with A[i] an array of length k

3条回答
  •  别那么骄傲
    2021-02-01 04:38

    I know it's rather tacky to answer one's own question, but I've just figured this out and it is closer to an answer than it is to part of the question. However, this is not a complete answer and will not get accepted, so please post thoughts if anyone can improve this.

    The minimum number of swaps, say m, for k=2 is bounded by:

    2 * (n choose 2) >= m >= (2n choose 2) / 3
    

    Why does this work?

    The upper bound comes doing a bubble sort on the first elements of the arrays, followed by a bubble sort on the second elements of the arrays. That part isn't so tricky.

    The lower bound is a bit tricky, but here's how I came to it. Let's count the number of passes, where a pass happens when a larger number moves from the left of a smaller number to the right of that number. This can happen in 1 swap of a and b, with a larger and in the array to the left of b. It can also take 2 swaps if a is moved to the array with b in one swap and then moves on in a later swap. To keep track of things correctly, count passes in halves in this case. To make counting easier, it also counts as a pass when two of the same number split up and then recombine.

    The array is fully sorted after (2n choose 2) passes, so the only question is how many passes can happen with one swap. Here's a simple example where a and c are swapped:

    ... [a,b] , [c,d] ... 
    ... [c,b] , [a,d] ... 
    

    Now let's count the maximum number of passes that can have happened:

    • Since a > c, we definitely get 1 full pass.
    • If a > b, then we get 1/2 pass because a must have been left of b at some point.
    • If a > d, then we get 1/2 pass because a will be right of d at some point.
    • If c < d, then we get 1/2 pass because d must have been left of c at some point.
    • If c < b, then we get 1/2 pass because b will be right of c at some point.

    Therefore the best you can do on a swap is to get 3 passes (1 full and 4 halves).

    Why is this not a complete answer?

    I have no idea if the lower bound is always attainable! I don't think it is, and, despite several failed attempts, I can't code up an algorithm that achieves it.

提交回复
热议问题