Selection sort implementation

This commit is contained in:
Nikunj Gandhi 2019-07-30 16:44:46 -04:00
parent db90a53e38
commit 07cd60e843
2 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,72 @@
package com.baeldung.algorithms.selectionsort;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SelectionSort {
/*public static void main(final String args[]) {
int[] a = { 5, 4, 1, 6, 2 };
System.out.println("Unsorted array");
System.out.println(IntStream.of(a)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
a = sortAscending(a);
System.out.println("Ascending Sorted array");
System.out.println(IntStream.of(a)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
a = sortDescending(a);
System.out.println("Descending Sorted array");
System.out.println(IntStream.of(a)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
}*/
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;
}
System.out.println("Iteration No. " + (i + 1));
System.out.println(IntStream.of(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
}
}
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;
}
System.out.println("Iteration No. " + (i + 1));
System.out.println(IntStream.of(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
}
}
}

View File

@ -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);
}
}