Skip to content

Commit 71db72a

Browse files
nikunjgandhi1987jzheaux
authored andcommitted
Selection Sort Implementation (eugenp#7454)
* Selection sort implementation * Selection sort implementation
1 parent f90828b commit 71db72a

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.algorithms.selectionsort;
2+
3+
public class SelectionSort {
4+
5+
public static void sortAscending(final int[] arr) {
6+
for (int i = 0; i < arr.length - 1; i++) {
7+
int minElementIndex = i;
8+
for (int j = i + 1; j < arr.length; j++) {
9+
if (arr[minElementIndex] > arr[j]) {
10+
minElementIndex = j;
11+
}
12+
}
13+
14+
if (minElementIndex != i) {
15+
int temp = arr[i];
16+
arr[i] = arr[minElementIndex];
17+
arr[minElementIndex] = temp;
18+
}
19+
}
20+
}
21+
22+
public static void sortDescending(final int[] arr) {
23+
for (int i = 0; i < arr.length - 1; i++) {
24+
int maxElementIndex = i;
25+
for (int j = i + 1; j < arr.length; j++) {
26+
if (arr[maxElementIndex] < arr[j]) {
27+
maxElementIndex = j;
28+
}
29+
}
30+
31+
if (maxElementIndex != i) {
32+
int temp = arr[i];
33+
arr[i] = arr[maxElementIndex];
34+
arr[maxElementIndex] = temp;
35+
}
36+
}
37+
}
38+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.algorithms.selectionsort;
2+
3+
import static org.junit.Assert.*;
4+
import static org.junit.Assert.assertArrayEquals;
5+
6+
import org.junit.Test;
7+
8+
public class SelectionSortUnitTest {
9+
10+
@Test
11+
public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
12+
int[] input = { 5, 4, 1, 6, 2 };
13+
SelectionSort.sortAscending(input);
14+
int[] expected = {1, 2, 4, 5, 6};
15+
assertArrayEquals("the two arrays are not equal", expected, input);
16+
}
17+
18+
@Test
19+
public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
20+
int[] input = { 5, 4, 1, 6, 2 };
21+
SelectionSort.sortDescending(input);
22+
int[] expected = {6, 5, 4, 2, 1};
23+
assertArrayEquals("the two arrays are not equal", expected, input);
24+
}
25+
}

0 commit comments

Comments
 (0)