Selection Sort Implementation (#7454)
* Selection sort implementation * Selection sort implementation
This commit is contained in:
parent
f90828bfc0
commit
71db72a68a
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user