Analyze the time complexity of the algorithm below Use the B

Analyze the time complexity of the algorithm below.

Use the Big- notation: T(n)=(?). Provide justification for your result.

BubbleSort(A,n)

1 for (i=1;i<=n-1;i++)

3 for (j=n;j>=i+1;j--)

4 if (A[j-1]>A[j])

5 swap(A[j-1], A[j])

Solution

the time complexity for the bellow code is calculated by yhe no.of execution cycles it takes.
bellow is the running time calculation:


code: time: explanation:   
----------------------- ------------------------ ------------------------------------
BubbleSort(A,n) 0 it does not take any cpu time.so the execution time is 0
1 for (i=1;i<=n-1;i++) N-1 it started from 1 and repeate for N-1 times
3 for (j=n;j>=i+1;j--) (N-1)-1 this will executes 1 time less than above loop.
4 if (A[j-1]>A[j]) 1 for simple comparision
5 swap(A[j-1], A[j]) 1 for swapping single element.


total:= 0+(N-1)+(N-1)-1+1+1
-------- >>> (N-1)+(N-1)+1
TIME COMPLEXITY======= 2(N-1)+1


bubble sort:
best case time complexity:=O(n)
average and worst case:O(n^2)

Analyze the time complexity of the algorithm below. Use the Big- notation: T(n)=(?). Provide justification for your result. BubbleSort(A,n) 1 for (i=1;i<=n-1

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site