diff --git a/src/main/java/com/ordestiny/tdd/algorithms/SortingAlgorithms.java b/src/main/java/com/ordestiny/tdd/algorithms/SortingAlgorithms.java new file mode 100644 index 0000000..3eca593 --- /dev/null +++ b/src/main/java/com/ordestiny/tdd/algorithms/SortingAlgorithms.java @@ -0,0 +1,29 @@ +package com.ordestiny.tdd.algorithms; + +public class SortingAlgorithms { + + /** + * Sorting algorithm that works by repeatedly swapping the adjacent elements if they are in decreasing order. + * @param array + */ + public static int[] bubbleSort(int[] array) { + for (int i = 0; i < array.length - 1; i++) + for (int j = i + 1; j < array.length; j++) + if (array[i] > array[j]) + swap(i, j, array); + return array; + } + + /** + * Swaps values at given indices for an array. + * @param i + * @param j + * @param array + */ + private static void swap(int i, int j, int[] array) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + +} diff --git a/src/test/java/com/ordestiny/tdd/algorithms/BubbleSortTest.java b/src/test/java/com/ordestiny/tdd/algorithms/BubbleSortTest.java new file mode 100644 index 0000000..d36ffa0 --- /dev/null +++ b/src/test/java/com/ordestiny/tdd/algorithms/BubbleSortTest.java @@ -0,0 +1,22 @@ +package com.ordestiny.tdd.algorithms; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class BubbleSortTest { + + private final int[] notSortedArray = {8, 7, 6, 5, 4, 3, 2, 1, 0}; + private final int[] sortedArray = {0, 1, 2, 3, 4, 5, 6, 7, 8}; + + @Test + public void bubbleSort_IntegerArray_notSorted() { + assertArrayEquals(sortedArray, SortingAlgorithms.bubbleSort(notSortedArray)); + } + + @Test + public void bubbleSort_IntegerArray_sorted() { + assertArrayEquals(sortedArray, SortingAlgorithms.bubbleSort(sortedArray)); + } + +}