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 | [reply] |
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.
| [reply] |