BAEL-1211 Bubble Sort in Java (#2744)

* BAEL-815 Introduction to JGraphT

* BAEL-815 Move code from libraries to algorithms

* BAEL-1211 Bubble Sort in Java

* BAEL-1211 Bubble Sort in Java

* BAEL-1211 Bubble Sort in Java

* BAEL-1211 Bubble Sort in Java

* BAEL-1211 Fix conflict
This commit is contained in:
Parth Karia 2017-10-15 22:27:01 +05:30 committed by maibin
parent 0b5fbdc53e
commit eece3d02ba
2 changed files with 67 additions and 0 deletions

View File

@ -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++;
}
}
}

View File

@ -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);
}
}