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

后端 未结 1 1329
星月不相逢
星月不相逢 2021-01-28 14:02
for(int i=0; i array[i+1]){
    int temp = array[i];
    array[i] = array[i+1];
    array[i+1]=temp;
    i=-1;
  } 
}
         


        
1条回答
  •  清酒与你
    2021-01-28 14:36

    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).

    0 讨论(0)
提交回复
热议问题