0% found this document useful (0 votes)
20 views6 pages

Bubble Sort Algorithm Explained

Uploaded by

tamirubarasa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views6 pages

Bubble Sort Algorithm Explained

Uploaded by

tamirubarasa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Page 1 of 6

Bubble Sort Algorithm


Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based
algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets as its
average and worst case complexity are of O(n2) where n is the number of items.

Bubble Sort Algorithm


Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging
adjacent elements, if necessary. When no exchanges are required, the file is sorted.

We assume list is an array of n elements. We further assume that swap function swaps
the values of the given array elements.

Step 1 − Check if the first element in the input array is greater than the next element in
the array.

Step 2 − If it is greater, swap the two elements; otherwise move the pointer forward in
the array.

Step 3 − Repeat Step 2 until we reach the end of the array.

Step 4 − Check if the elements are sorted; if not, repeat the same process (Step 1 to
Step 3) from the last element of the array to the first.

Step 5 − The final output achieved is the sorted array.

Algorithm: Sequential-Bubble-Sort (A)


fori ← 1 to length [A] do
for j ← length [A] down-to i +1 do
if A[A] < A[j-1] then
Exchange A[j] ⟷ A[j-1]

Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the
whole array is completely sorted in an ascending order. This may cause a few complexity
issues like what if the array needs no more swapping as all the elements are already
ascending.

To ease-out the issue, we use one flag variable swapped which will help us see if any
swap has happened or not. If no swap has occurred, i.e. the array requires no more
processing to be sorted, it will come out of the loop.

[Link] 1/6
Page 2 of 6

Pseudocode of bubble sort algorithm can be written as follows −

voidbubbleSort(int numbers[], intarray_size){


inti, j, temp;
for (i = (array_size - 1); i>= 0; i--)
for (j = 1; j <= i; j++)
if (numbers[j-1] > numbers[j]){
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}

Analysis
Here, the number of comparisons are

1 + 2 + 3 + ... + (n - 1) = n(n - 1)/2 = O(n2)

Clearly, the graph shows the n2 nature of the bubble sort.

In this algorithm, the number of comparison is irrespective of the data set, i.e. whether
the provided input elements are in sorted order or in reverse order or at random.

Memory Requirement
From the algorithm stated above, it is clear that bubble sort does not require extra
memory.

Example
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping
it short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is
greater.

[Link] 2/6
Page 3 of 6

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

We know then that 10 is smaller 35. Hence they are not sorted. We swap these values. We
find that we have reached the end of the array. After one iteration, the array should look
like this −

[Link] 3/6
Page 4 of 6

To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sort learns that an array is completely sorted.

[Link] 4/6
Page 5 of 6

Now we should look into some practical aspects of bubble sort.

Implementation
One more issue we did not address in our original algorithm and its improvised
pseudocode, is that, after every iteration the highest values settles down at the end of the
array. Hence, the next iteration need not include already sorted elements. For this
purpose, in our implementation, we restrict the inner loop to avoid already sorted values.

C C++ Java Python

Open Compiler

#include<iostream>
using namespace std;
void bubbleSort(int *array, int size){
for(int i = 0; i<size; i++) {
int swaps = 0; //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++) {
if(array[j] > array[j+1]) { //when the current item is bigger than
next
int temp;
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
swaps = 1; //set swap flag
}
}
if(!swaps)
break; // No swap in this pass, so array is sorted
}
}
int main(){
int n;
n = 5;
int arr[5] = {67, 44, 82, 17, 20}; //initialize an array
cout << "Array before Sorting: ";
for(int i = 0; i<n; i++)
cout << arr[i] << " ";
cout << endl;
bubbleSort(arr, n);
cout << "Array after Sorting: ";
for(int i = 0; i<n; i++)

[Link] 5/6
Page 6 of 6

cout << arr[i] << " ";


cout << endl;
}

Output
Array before Sorting: 67 44 82 17 20
Array after Sorting: 17 20 44 67 82

[Link] 6/6

Common questions

Powered by AI

The simplicity and absence of additional memory requirements in Bubble Sort make it suitable for educational purposes and small datasets where memory constraints are critical. It is easy to implement and analyze, serving as a basic introduction to sorting concepts. In scenarios with extremely limited system resources where additional memory allocation is prohibitive, Bubble Sort's lack of memory overhead can be advantageous, though this scenario is largely theoretical given the inefficiencies demonstrated in time complexity .

The primary practical limitation of Bubble Sort, despite theoretical optimizations like early termination and ignoring already sorted sections, is its inherent time complexity of O(n^2) in the average and worst-case scenarios. This results in excessive computational time for large datasets. While some modifications improve performance on nearly sorted arrays, they do not address the fundamental inefficiency compared to algorithms like Quick Sort or Merge Sort, which offer faster average-case performance and scalability .

Pass-wise optimizations in Bubble Sort, such as implementing a flag to stop the algorithm when no swaps are needed, reduce the number of comparisons necessary in sorted or nearly sorted datasets. By terminating early and excluding sorted elements from future passes, the algorithm minimizes unnecessary operations, making it more practical in scenarios where output is close to the input ordering. However, these optimizations do not improve the worst-case time complexity of O(n^2), limiting the algorithm's applicability for datasets expected to be unordered .

Unlike more complex sorting algorithms that may require additional memory allocation (e.g., merging sorted halves), Bubble Sort does not require extra memory beyond the initial input array. This characteristic makes it memory efficient, but it does not compensate for its inefficiency in time complexity, making it impractical for large data sets despite its low memory requirement .

The initial ordering of the array significantly affects the performance of Bubble Sort. If the array is already sorted, the optimized Bubble Sort with a 'swapped' flag will terminate early, resulting in a best-case time complexity of O(n). However, if the array is in reverse order, it will take the maximum number of swaps and iterations, manifesting the worst-case time complexity of O(n^2). In contrast, other algorithms like Quick Sort may still perform well regardless of the initial order due to their divide-and-conquer approach, while algorithms like Merge Sort maintain a consistent O(n log n) performance regardless of initial order .

In the optimized implementation of the Bubble Sort algorithm, each pass through the array ensures that the largest unsorted element is moved to its correct position at the end. This allows the next passes to exclude elements that are already sorted in previous iterations. The optimized implementation uses a decreasing loop range for each pass, effectively reducing the number of elements considered, thereby improving the average time performance in some cases .

The Bubble Sort algorithm determines whether elements should be swapped by comparing each pair of adjacent elements in the array. If the current element is greater than the next, they are swapped. This makes Bubble Sort a comparison-based algorithm. Its efficiency is affected because Bubble Sort has an average and worst-case time complexity of O(n^2), making it inefficient for large data sets .

The iterative nature and pseudocode structure of Bubble Sort demonstrate its step-by-step sorting approach by detailing a series of nested loops that repeatedly pass through the array. The outer loop iterates over the total length of the array, and the inner loop compares and swaps adjacent elements. This structured repetition exemplifies a methodical approach where each pass aims to place the largest unsorted element to its final position, ensuring gradual progression towards a fully sorted array .

Bubble Sort is considered unsuitable for large datasets because it has an average and worst-case time complexity of O(n^2), meaning its operation time increases quadratically with the number of elements, resulting in slow performance on larger datasets. Alternative sorting algorithms like Merge Sort, Quick Sort, or Heap Sort have better time complexities (O(n log n) on average), making them more efficient for larger data sets .

The 'swapped' flag in the Bubble Sort algorithm helps to avoid unnecessary passes over the array once it is sorted. If during a complete pass through the array no elements are swapped, the flag remains false, indicating that the array is sorted and the algorithm can terminate early. This improvement becomes effective when the array becomes sorted within fewer passes than its maximum, thereby reducing the number of comparisons needed .

You might also like