diff --git a/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java b/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java index f5080efa40..a561072b2e 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java @@ -19,11 +19,13 @@ public class BubbleSort { void optimizedBubbleSort(Integer[] arr) { int i = 0, n = arr.length; + boolean swapNeeded = true; while (i < n - 1 && swapNeeded) { swapNeeded = false; - for (int j = i + 1; j < n - i; j++) { + for (int j = 1; j < n - i; j++) { if (arr[j - 1] > arr[j]) { + int temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp;