Skip to content

Commit 0d07279

Browse files
authored
Refactor BubbleSort to use a temporary variable for swap
1 parent a0f6b0d commit 0d07279

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

src/main/java/com/thealgorithms/sorts/BubbleSort.java

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,26 @@ class BubbleSort implements SortAlgorithm {
2222
* @return the sorted array.
2323
*/
2424
@Override
25-
public <T extends Comparable<T>> T[] sort(T[] array) {
26-
for (int i = 1, size = array.length; i < size; ++i) {
27-
boolean swapped = false;
28-
for (int j = 0; j < size - i; ++j) {
29-
if (SortUtils.greater(array[j], array[j + 1])) {
30-
SortUtils.swap(array, j, j + 1);
31-
swapped = true;
32-
}
33-
}
34-
if (!swapped) {
35-
break;
25+
public <T extends Comparable<T>> T[] sort(T[] array) {
26+
for (int i = 1, size = array.length; i < size; ++i) {
27+
boolean swapped = false;
28+
29+
for (int j = 0; j < size - i; ++j) {
30+
if (SortUtils.greater(array[j], array[j + 1])) {
31+
32+
// Swap using a temporary variable
33+
T temp = array[j];
34+
array[j] = array[j + 1];
35+
array[j + 1] = temp;
36+
37+
swapped = true;
3638
}
3739
}
38-
return array;
40+
41+
if (!swapped) {
42+
break;
43+
}
3944
}
45+
46+
return array;
4047
}

0 commit comments

Comments
 (0)