Skip to content

Commit 6f9b7d2

Browse files
committed
Add selection sort code
1 parent b546738 commit 6f9b7d2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package sort;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class SelectionSort {
9+
10+
/*
11+
TASK
12+
*/
13+
14+
@Test
15+
public void test() {
16+
int[] arr1 = {};
17+
int[] sortedArr1 = {};
18+
assertThat(solution(arr1), is(sortedArr1));
19+
int[] arr2 = {6,4,1,8,9,2,7,5,3};
20+
int[] sortedArr2 = {1,2,3,4,5,6,7,8,9};
21+
assertThat(solution(arr2), is(sortedArr2));
22+
int[] arr3 = {1};
23+
int[] sortedArr3 = {1};
24+
assertThat(solution(arr3), is(sortedArr3));
25+
26+
int[] arr = {1,2,3};
27+
int[] chagedArr = {1,3,2};
28+
assertThat(swapValue(arr, 1,2), is(chagedArr));
29+
}
30+
31+
public int[] solution(int[] arr) {
32+
if (arr == null) return null;
33+
int[] result = arr;
34+
int maxPos;
35+
36+
for (int i = 0; i < result.length - 1; i++) {
37+
maxPos = i;
38+
for (int k = i + 1g; k < result.length; k++) {
39+
if (result[maxPos] > result[k]) {
40+
maxPos = k;
41+
}
42+
}
43+
result = swapValue(result, i, maxPos);
44+
}
45+
return result;
46+
}
47+
48+
private int[] swapValue(int[] arr, int a, int b) {
49+
int temp = arr[a];
50+
arr[a] = arr[b];
51+
arr[b] = temp;
52+
return arr;
53+
}
54+
}

0 commit comments

Comments
 (0)