# Algorithms | Sorting | Question 10

• Difficulty Level : Basic
• Last Updated : 28 Jun, 2021

What is the best time complexity of bubble sort?

(A) N^2
(B) NlogN
(C) N
(D) N(logN)^2

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
Recommended Articles
Page :