问题
for(int i=0; i<array.length -1; i++){
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1]=temp;
i=-1;
}
}
I think the code sorts the input array and that its worst case complexity is O(n).
What is the correct big-O complexity of this code?
回答1:
It's O(n^3), and it's an inefficient version of bubble sort.
The code scans through the array looking for the first adjacent pair of out-of-order elements, swaps them, and then restarts from the beginning of the array.
In the worst case, when the array is in reverse order, the recurrence relation the code satisfies is:
T(n+1) = T(n) + n(n-1)/2
That's because the first n elements will be sorted by the algorithm before the code reaches the n+1'th element. Then the code repeatedly scans forward to find this new element, and moves it one space back. That takes time n + (n-1) + ... + 1 = n(n-1)/2.
That solves to Theta(n^3).
来源:https://stackoverflow.com/questions/61956966/what-is-complexity-of-this-code-big-o-is-that-linear