Presentation is loading. Please wait.

Presentation is loading. Please wait.

Analysis of Bubble Sort and Loop Invariant

Similar presentations


Presentation on theme: "Analysis of Bubble Sort and Loop Invariant"— Presentation transcript:

1 Analysis of Bubble Sort and Loop Invariant

2 N-1 Iteration 77 12 35 42 5 101 N - 1 5 42 12 35 77 101 42 5 35 12 77 101 42 35 5 12 77 101 42 35 12 5 77 101

3 Bubble Sort Algorithm Bubble-Sort( A ): for i = 1 … (N – 1):
for k = 1 … (N – 1): if A[k] > A[k+1]: Swap( A, k, k+1 ) To do N-1 iterations To bubble a value Inner loop Outer loop Python Code in

4 Bubble Sort Time Complexity
Best-Case Time Complexity The scenario under which the algorithm will do the least amount of work (finish the fastest) Worst-Case Time Complexity The scenario under which the algorithm will do the largest amount of work (finish the slowest)

5 Bubble Sort Time Complexity
Called Linear Time O(N2) Order-of-N-square Best-Case Time Complexity Array is already sorted (N-1) + (N-2) + (N-3) + …. + (1) = (N-1)* N / 2 comparisons Worst-Case Time Complexity Need N-1 iterations Called Quadratic Time O(N2) Order-of-N-square

6 Loop Invariant for i = 1 … (N – 1): for k = 1 … (N – 1):
It is a condition or property that is guaranteed to be correct with each iteration in the loop Usually used to prove the correctness of the algorithm for i = 1 … (N – 1): for k = 1 … (N – 1): if A[k] > A[k+1]: Swap( A, k, k+1 ) Inner loop Outer loop To bubble a value To do N-1 iterations

7 Loop Invariant for Bubble Sort
for i = 1 … (N – 1): for k = 1 … (N – 1): if A[k] > A[k+1]: Swap( A, k, k+1 ) Inner loop Outer loop To bubble a value To do N-1 iterations By the end of iteration i  the right-most i items (largest) are sorted and in place

8 N-1 Iterations 77 12 35 42 5 101 N - 1 1st 5 42 12 35 77 101 2nd 42 5 35 12 77 101 3rd 42 35 5 12 77 101 4th 42 35 12 5 77 101 5th

9 Correctness of Bubble Sort (using Loop Invariant)
Bubble sort has N-1 Iterations Invariant: By the end of iteration i  the right-most i items (largest) are sorted and in place Then: After the N-1 iterations  The right-most N-1 items are sorted This implies that all the N items are sorted


Download ppt "Analysis of Bubble Sort and Loop Invariant"

Similar presentations


Ads by Google