삽입 정렬

삽입 정렬

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class InsertionSort{
public int[] insertionSort(int[] s){
int n = s.length;
int val; // 임시 저장 공간
int j;
for(int i = 1; i < n; i++){
// 현재 위치의 요소를 임시로 저장
val = s[i];
j = i - 1;
// 현재 위치 앞의 요소보다 작다면 서로 위치를 바꿈
while((j >= 0) && (val < s[j])){
s[j + 1] = s[j];
j--;
}
s[j + 1] = val;
}
return s;
}
// 배열을 출력하는 메소드
public void display(int[] s){
for(int i = 0; i < s.length; i++){
System.out.print(s[i] + " ");
}
System.out.println();
}
public static void main(String[] args){
InsertionSort s = new InsertionSort();
s.display(s.insertionSort(new int[]{8, 13, 20, 27, 16}));
}
}
Share Comments