in reply to Fast way to check if a sort was doen

Hi,
So you've done something like @sorted = sort @array;

How would it be if you did a Digest::MD5::md5("@sorted"); and a Digest::MD5::md5("@array"); and checked the returned strings for equivalence ?

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: Fast way to check if a sort was doen
by archfool (Monk) on Jun 28, 2007 at 15:28 UTC
    I believe this would still be O(2n). Even if Digest::MD5::md5 is really written in C, so it might be FASTER, but it's the same amount of work. i.e. you are still running through each element of both arrays.
      But I think it is the fastest way. If I would test for a change in the sort sub, there would be maybe more comparisons. I think I use this because it also works for "reverse sort @array".

      Thanks,
      Andre
        Outaspace,
        Depending on how you interpret your question, the solution can be done in worst case O(N). If the only thing that is desired is knowing if sorting the array will change the order, then the algorithm is simple.

        Walk the original array testing if each element is in the position it is supposed to be (same as your sort block). If you get to the end, your array is already sorted and there is no need to sort it. If you find an element out of order than you know the array needs to be sorted (which will change the order).

        The trick is that you can't actually both know that the array needs to be sorted and sort it in better than O(N). At least I couldn't think of a way in the 2 minutes I spent thinking about it.

        Cheers - L~R