Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Algorithms | Sorting | Question 10

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads