forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
40 lines (38 loc) · 1.12 KB
/
BubbleSort.java
File metadata and controls
40 lines (38 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
}
}