Bubble Sorting in Data Structure

Bubble Sort:

Bubble Sort can be defined as a comparison-based sort by checking each adjacent pair of items in a list, in turn, swapping the items if necessary and repeating the pass through the list until no swaps are done.

Bubble Sorting in Data Structure

Algorithm for Bubble Sort:

Algorithm fnBubbleSort(P[],n)
for(Iteration=1;Iteration {
for(j=0;j<n-Iteration; j++) { if(P[j]>P[j+1])
} // End of Algorithm

Time complexity of Bubble Sort:

1. Best Case: The array is in sorted order. Hence swap will remain false after the first iteration and so the process ends. Therefore the total number of comparisons made will be decided by the inner for the first iteration which is n-1.
Tb(n) = O(n)

2. Average Case: On average the comparison made in the inner loop is (k-1)/2
Therefore, Ta(n) = O(n2)

3. Worst Case: The array P[] is in reverse order. So for the first iteration, n-1 comparisons are needed, for the second iteration n-2 comparisons are needed and so on. Hence in the worst case:
Therefore, Tw(n) = O(n2)

Space complexity of Bubble Sort:

The space complexity is O(1), just a few scalar variables. Here, we don’t count the size of the array being sorted because that is given, not created specifically for this algorithm.