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
35 lines (32 loc) · 973 Bytes
/
BubbleSort.java
File metadata and controls
35 lines (32 loc) · 973 Bytes
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
package com.thealgorithms.sorts;
import static com.thealgorithms.sorts.SortUtils.*;
/**
* @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.
*
* @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 (greater(array[j], array[j + 1])) {
swap(array, j, j + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
}
return array;
}
}