Open In App
Related Articles

Algorithms | Sorting | Question 10

Improve Article
Improve
Save Article
Save
Like Article
Like

What is the best time complexity of bubble sort?

(A)

N^2

(B)

NlogN

(C)

N

(D)

N(logN)^2



Answer: (C)

Explanation:

The bubble sort is at its best if the input data is sorted. i.e. If the input data is sorted in the same order as expected output. This can be achieved by using one boolean variable. The boolean variable is used to check whether the values are swapped at least once in the inner loop. Consider the following code snippet: 

int main()
{   
    int arr[] = {10, 20, 30, 40, 50}, i, j, isSwapped;
    int n = sizeof(arr) / sizeof(*arr);
    isSwapped = 1;
    for(i = 0; i < n - 1 && isSwapped; ++i)
    {
        isSwapped = 0;
        for(j = 0; j < n - i - 1; ++j)
            if (arr[j] > arr[j + 1])
            {
                swap(&arr[j], &arr[j + 1]);
                isSwapped = 1;
            }
    }
    for(i = 0; i < n; ++i)
        printf(\"%d \", arr[i]);
    return 0;
}

Please observe that in the above code, the outer loop runs only once.


Quiz of this Question
Please comment below if you find anything wrong in the above post

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads