how to calculate Bubble sort Time Complexity

前端 未结 7 1265
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 12:29

I was trying to understand the Data Structure and different algorithm, then i got confused to measure the Bubble sort time complexity.

for (c = 0; c < ( n         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 12:40

    Let's go through the cases for Big O for Bubble Sort

    Case 1) O(n) (Best case) This time complexity can occur if the array is already sorted, and that means that no swap occurred and only 1 iteration of n elements

    Case 2) O(n^2) (Worst case) The worst case is if the array is already sorted but in descending order. This means that in the first iteration it would have to look at n elements, then after that it would look n - 1 elements (since the biggest integer is at the end) and so on and so forth till 1 comparison occurs. Big-O = n + n - 1 + n - 2 ... + 1 = (n*(n + 1))/2 = O(n^2)

    In your example, it may not examine these many elements in each phase as the array is not in descending order.

提交回复
热议问题