Skip to content

Commit b546738

Browse files
committed
Add insertion sort code
1 parent ac4cae4 commit b546738

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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 InsertionSort {
9+
10+
/*
11+
TASK
12+
Insertion sort를 구현한다.
13+
*/
14+
15+
@Test
16+
public void test() {
17+
int[] arr1 = {};
18+
int[] sortedArr1 = {};
19+
assertThat(solution(arr1), is(sortedArr1));
20+
int[] arr2 = {6,4,1,8,9,2,7,5,3};
21+
int[] sortedArr2 = {1,2,3,4,5,6,7,8,9};
22+
assertThat(solution(arr2), is(sortedArr2));
23+
int[] arr3 = {1};
24+
int[] sortedArr3 = {1};
25+
assertThat(solution(arr3), is(sortedArr3));
26+
}
27+
28+
public int[] solution(int[] arr) {
29+
if (arr == null) return null;
30+
int temp;
31+
for (int i = 1; i < arr.length; i++) {
32+
temp = arr[i];
33+
int k;
34+
for (k = i - 1; k >= 0; k--) {
35+
if (temp >= arr[k]) {
36+
break;
37+
}
38+
arr[k + 1] = arr[k];
39+
}
40+
arr[k + 1] = temp;
41+
}
42+
43+
return arr;
44+
}
45+
}

0 commit comments

Comments
 (0)