Question

19.5 (Enhanced Bubble Sort) Explain why bubble sort is an O(n^2) algorithm.

19.5 (Enhanced Bubble Sort) Explain why bubble sort is an O(n^2) algorithm.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
void bubbleSort(int arr[], int n)
{
    int i, j, temp;
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}


This bubble sort code has a nested for loop

First for loop running for i values from 0 to n-1
So, Number of values for i = n-1

Inner for loop running for j values from 0 to n-i-1
So, in worst case inner for loop running for n-1 times 

Total time complexity
= O((n-1)(n-1))
= O(n^2)
Add a comment
Know the answer?
Add Answer to:
19.5 (Enhanced Bubble Sort) Explain why bubble sort is an O(n^2) algorithm.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT