What is complexity of this code? (Big O) Is that linear?

99封情书 提交于 2020-06-17 09:41:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!