diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/selectionsort/SelectionSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/selectionsort/SelectionSort.java new file mode 100644 index 0000000000..17e95edf06 --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/selectionsort/SelectionSort.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.selectionsort; + +public class SelectionSort { + + public static void sortAscending(final int[] arr) { + for (int i = 0; i < arr.length - 1; i++) { + int minElementIndex = i; + for (int j = i + 1; j < arr.length; j++) { + if (arr[minElementIndex] > arr[j]) { + minElementIndex = j; + } + } + + if (minElementIndex != i) { + int temp = arr[i]; + arr[i] = arr[minElementIndex]; + arr[minElementIndex] = temp; + } + } + } + + public static void sortDescending(final int[] arr) { + for (int i = 0; i < arr.length - 1; i++) { + int maxElementIndex = i; + for (int j = i + 1; j < arr.length; j++) { + if (arr[maxElementIndex] < arr[j]) { + maxElementIndex = j; + } + } + + if (maxElementIndex != i) { + int temp = arr[i]; + arr[i] = arr[maxElementIndex]; + arr[maxElementIndex] = temp; + } + } + } +} \ No newline at end of file diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java new file mode 100644 index 0000000000..85efd1d3da --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.selectionsort; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class SelectionSortUnitTest { + + @Test + public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() { + int[] input = { 5, 4, 1, 6, 2 }; + SelectionSort.sortAscending(input); + int[] expected = {1, 2, 4, 5, 6}; + assertArrayEquals("the two arrays are not equal", expected, input); + } + + @Test + public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() { + int[] input = { 5, 4, 1, 6, 2 }; + SelectionSort.sortDescending(input); + int[] expected = {6, 5, 4, 2, 1}; + assertArrayEquals("the two arrays are not equal", expected, input); + } +}