From 0d072792fcb11eb3777e872ec2bccfe23b2cbccd Mon Sep 17 00:00:00 2001 From: Ajay Verma Date: Sat, 29 Aug 2026 17:56:00 +0530 Subject: [PATCH] Refactor BubbleSort to use a temporary variable for swap --- .../com/thealgorithms/sorts/BubbleSort.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSort.java b/src/main/java/com/thealgorithms/sorts/BubbleSort.java index d2eca3506c2d..be14e750f9c5 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSort.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSort.java @@ -22,19 +22,26 @@ class BubbleSort implements SortAlgorithm { * @return the sorted array. */ @Override - public > 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; +public > 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])) { + + // Swap using a temporary variable + T temp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = temp; + + swapped = true; } } - return array; + + if (!swapped) { + break; + } } + + return array; }