Java Bubble Sort
Very simple Bubble Sort code in java with unit-test.
public class BubbleSort {
public static void sort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
Unit-test to check that implementation is correct:
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class BubbleSortTest {
@Test
void testEmptyArray() {
int[] array = {};
BubbleSort.sort(array);
assertThat(array).isEmpty();
}
@Test
void testSingleElement() {
int[] array = {5};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{5});
}
@Test
void testTwoElements() {
int[] array = {2, 1};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2});
}
@Test
void testThreeElements() {
int[] array = {3, 1, 2};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2, 3});
}
@Test
void testFourElements() {
int[] array = {3, 1, 4, 2};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2, 3, 4});
}
@Test
void testFiveElements() {
int[] array = {3, 4, 2, 5, 1};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2, 3, 4, 5});
}
@Test
void testSortedArray() {
int[] array = {1, 2, 3, 4, 5};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2, 3, 4, 5});
}
@Test
void testReversedArray() {
int[] array = {5, 4, 3, 2, 1};
BubbleSort.sort(array);
assertThat(array).isEqualTo(new int[]{1, 2, 3, 4, 5});
}
}
To run the unit-test, JUnit Jupiter and AssertJ libraries are required.