Why does Bubble sort have O(n) time complexity in best-case performance?
The best case for Bubble Sort Occurs when the given array is sorted array.
We will be able to get to the answer by making a small change to the traditional Bubble Sort Algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void bubbleSort(int* Arr, int len)
{
int flag = 1;
for(int i=0; i<len-1; i++)
{
for(int j=0; j<len-i-1; j++)
{
if(Arr[j] > Arr[j+1])
{
flag = 0;
swap(Arr[j], Arr[j+1]);
}
}
if(flag == 1)
{
cout<<"Array is already sorted"<<endl;
}
}
}
Now if the array is already sorted, then flag=1 at the end of the first pass. So when this condition is met, we break out of the loop. Since we only pass through n-1 elements in the best case, the complexity is linear as opposed to the Quadratic Complexity of Bubble-Sort.
So it has O(n) complexity in Best Case.