diff --git a/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java b/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java new file mode 100644 index 0000000000..aa5e085153 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java @@ -0,0 +1,41 @@ +package com.baeldung.algorithms.bubblesort; + +import java.util.stream.IntStream; + +public class BubbleSort { + + public void bubbleSort(Integer[] arr) { + int n = arr.length; + IntStream.range(0, n - 1) + .forEach(i -> { + IntStream.range(i + 1, n - i) + .forEach(j -> { + if (arr[j - 1] > arr[j]) { + int temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + } + }); + }); + } + + public 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++) { + if (arr[j - 1] > arr[j]) { + int temp = arr[j - 1]; + arr[j - 1] = arr[j]; + arr[j] = temp; + swapNeeded = true; + } + } + if (!swapNeeded) + break; + i++; + } + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java new file mode 100644 index 0000000000..7774eb3e67 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.bubblesort; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class BubbleSortTest { + + @Test + public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.bubbleSort(array); + assertArrayEquals(array, sortedArray); + } + + @Test + public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.optimizedBubbleSort(array); + assertArrayEquals(array, sortedArray); + } +} \ No newline at end of file