Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/main/java/com/ordestiny/tdd/algorithms/SortingAlgorithms.java
Original file line number Diff line number Diff line change
@@ -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;
}

}
22 changes: 22 additions & 0 deletions src/test/java/com/ordestiny/tdd/algorithms/BubbleSortTest.java
Original file line number Diff line number Diff line change
@@ -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));
}

}