์ฝ์ ์ ๋ ฌ (Insertion Sort)
ํต์ฌ ์์
โข
์ ๋ ฌ๋ ๋ถ๋ถ๊ณผ ์ ๋ ฌ๋์ง ์์ ๋ถ๋ถ์ผ๋ก ๋๋์ด ์งํ
โข
๊ฐ ์์๋ฅผ ์ ์ ํ ์์น์ ์ฝ์
โข
in-place ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ์ถ๊ฐ ๋ฉ๋ชจ๋ฆฌ๊ฐ ๊ฑฐ์ ํ์ํ์ง ์์
์๊ฐ ๋ณต์ก๋
์ต์ ์ ๊ฒฝ์ฐ | O(n) |
ํ๊ท ์ ๊ฒฝ์ฐ | O(nยฒ) |
์ต์
์ ๊ฒฝ์ฐ | O(nยฒ) |
์ฃผ์ ํน์ง
โข
์์ ์ ๋ ฌ(Stable Sort)
โข
์์ ๋ฐ์ดํฐ์
์์ ํจ์จ์
โข
์ด๋ฏธ ์ ๋ ฌ๋ ๋ฐ์ดํฐ์ ๋ํด ๋งค์ฐ ํจ์จ์
โข
์ ์ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ
์์ ์ฝ๋
์ง์ ๊ตฌํ
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i]; // ํ์ฌ ์ฝ์
ํ ๊ฐ
int j = i - 1;
// key๋ณด๋ค ํฐ ๊ฐ์ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key; // ์ ์ ํ ์์น์ key ์ฝ์
}
}
public static void main(String[] args) {
int[] arr = { 5, 2, 9, 1, 5, 6 };
insertionSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Java
๋ณต์ฌ