Skip to content

Commit eece3d0

Browse files
parthkariamaibin
authored andcommitted
BAEL-1211 Bubble Sort in Java (eugenp#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
1 parent 0b5fbdc commit eece3d0

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.algorithms.bubblesort;
2+
3+
import java.util.stream.IntStream;
4+
5+
public class BubbleSort {
6+
7+
public void bubbleSort(Integer[] arr) {
8+
int n = arr.length;
9+
IntStream.range(0, n - 1)
10+
.forEach(i -> {
11+
IntStream.range(i + 1, n - i)
12+
.forEach(j -> {
13+
if (arr[j - 1] > arr[j]) {
14+
int temp = arr[j];
15+
arr[j] = arr[j - 1];
16+
arr[j - 1] = temp;
17+
}
18+
});
19+
});
20+
}
21+
22+
public void optimizedBubbleSort(Integer[] arr) {
23+
int i = 0, n = arr.length;
24+
boolean swapNeeded = true;
25+
while (i < n - 1 && swapNeeded) {
26+
swapNeeded = false;
27+
for (int j = i + 1; j < n - i; j++) {
28+
if (arr[j - 1] > arr[j]) {
29+
int temp = arr[j - 1];
30+
arr[j - 1] = arr[j];
31+
arr[j] = temp;
32+
swapNeeded = true;
33+
}
34+
}
35+
if (!swapNeeded)
36+
break;
37+
i++;
38+
}
39+
}
40+
41+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.algorithms.bubblesort;
2+
3+
import static org.junit.Assert.*;
4+
5+
import org.junit.Test;
6+
7+
public class BubbleSortTest {
8+
9+
@Test
10+
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
11+
Integer[] array = { 2, 1, 4, 6, 3, 5 };
12+
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
13+
BubbleSort bubbleSort = new BubbleSort();
14+
bubbleSort.bubbleSort(array);
15+
assertArrayEquals(array, sortedArray);
16+
}
17+
18+
@Test
19+
public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
20+
Integer[] array = { 2, 1, 4, 6, 3, 5 };
21+
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
22+
BubbleSort bubbleSort = new BubbleSort();
23+
bubbleSort.optimizedBubbleSort(array);
24+
assertArrayEquals(array, sortedArray);
25+
}
26+
}

0 commit comments

Comments
 (0)