package com.thealgorithms.sorts;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see SortAlgorithm
*/
class BubbleSort implements SortAlgorithm {
/**
* Implements generic bubble sort algorithm.
*
* Time Complexity:
* - Best case: O(n) – array is already sorted.
* - Average case: O(n^2)
* - Worst case: O(n^2)
*
* Space Complexity: O(1) – in-place sorting.
*
* @param array the array to be sorted.
* @param <T> the type of elements in the array.
* @return the sorted array.
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 1, size = array.length; i < size; ++i) {
boolean swapped = false;
for (int j = 0; j < size - i; ++j) {
if (SortUtils.greater(array[j], array[j + 1])) {
SortUtils.swap(array, j, j + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
}
return array;
}
}
Given an unsorted array of n elements, write a function to sort the array
O(n^2) Worst case performance
O(n) Best-case performance
O(n^2) Average performance
O(1) Worst case
arr[] = {10, 80, 40, 30}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 80, do nothing and continue
3. Index = 1, Number = 80
4. 80 > 40, swap 80 and 40
5. The array now is {10, 40, 80, 30}
6. Index = 2, Number = 80
7. 80 > 30, swap 80 and 30
8. The array now is {10, 40, 30, 80}
Repeat the Above Steps again
arr[] = {10, 40, 30, 80}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 40, do nothing and continue
3. Index = 1, Number = 40
4. 40 > 30, swap 40 and 30
5. The array now is {10, 30, 40, 80}
6. Index = 2, Number = 40
7. 40 < 80, do nothing
8. The array now is {10, 30, 40, 80}
Repeat the Above Steps again
arr[] = {10, 30, 40, 80}
Indexes: 0 1 2 3
1. Index = 0, Number = 10
2. 10 < 30, do nothing and continue
3. Index = 1, Number = 30
4. 30 < 40, do nothing and continue
5. Index = 2, Number = 40
6. 40 < 80, do nothing
Since there are no swaps in above steps, it means the array is sorted and we can stop here.
A video explaining the Bubble Sort Algorithm
Bubble sort is also known as Sinking sort.