-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
51 lines (42 loc) ยท 1.35 KB
/
InsertionSort.java
File metadata and controls
51 lines (42 loc) ยท 1.35 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
package sort;
import java.util.Scanner;
// ๋จ์ ์ฝ์
์ ๋ ฌ = ์ ํํ ์์๋ฅผ ๊ทธ๋ณด๋ค ๋ ์์ชฝ์ ์๋ง์ ์์น์ '์ฝ์
ํ๋' ์์
์ ๋ฐ๋ณตํ์ฌ ์ ๋ ฌํ๋ ์๊ณ ๋ฆฌ์ฆ
// ๊ณผ์
// 1.์ ๋ ฌ๋ ์ด์ ์ผ์ชฝ ๋์ ๋๋ฌ
// 2.tmp๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ key๋ฅผ ๊ฐ๋ ํญ๋ชฉ a[j]๋ฅผ ๋ฐ๊ฒฌ
// 3.๋๋ชจ๋ฅด๊ฐ ๋ฒ์น ์ ์ฉํ์ฌ ์กฐ๊ฑด ์ฑ๋ฆฝํ ๋๊น์ง ๋ฐ๋ณต
// ์กฐ๊ฑด(1.j๊ฐ 0๋ณด๋ค ํฌ๋ค 2.a[j-1]๊ฐ์ด tmp๋ณด๋ค ํฌ๋ค)
public class InsertionSort {
static void insertionSort(int[] a, int n) {
for(int i=1; i<n; i++) {
int j;
int tmp = a[i];
for(j = i; j>0 && a[j-1] > tmp; j--) {
a[j] = a[j-1];
}
a[j] = tmp;
}
}
// a[idx1]์ a[idx2]์ ๊ฐ์ ๋ฐ๊พผ๋ค
static void swap(int[] a, int idx1, int idx2) {
int t = a[idx1];
a[idx1] = a[idx2];
a[idx2] = t;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("๋จ์ ์ ํ ์ ๋ ฌ");
System.out.print("์์ ์ : ");
int nx = stdIn.nextInt();
int[] x = new int[nx];
for (int i = 0; i < nx; i++) {
System.out.print("x[" + i + "] : ");
x[i] = stdIn.nextInt();
}
insertionSort(x, nx); // ๋ฐฐ์ด x๋ฅผ ๋ฒ๋ธ ์ ๋ ฌํฉ๋๋ค
System.out.println("์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ์ต๋๋ค.");
for (int i = 0; i < nx; i++)
System.out.println("x[" + i + "]= " + x[i]);
stdIn.close();
}
}