# μ‚½μž… μ •λ ¬ (Insertion Sort)

written by sohyeon, hyemin πŸ’‘


# 1. μ‚½μž… μ •λ ¬μ΄λž€?

μ„ νƒν•œ μš”μ†Œλ₯Ό μ•Œλ§žμ€ μœ„μΉ˜μ— μ‚½μž…ν•˜λŠ” μž‘μ—…μ„ λ°˜λ³΅ν•˜μ—¬ μ •λ ¬ν•˜λŠ” μ•Œκ³ λ¦¬μ¦˜μ΄λ‹€.

자료 λ°°μ—΄μ˜ λͺ¨λ“  μš”μ†Œλ₯Ό μ•žμ—μ„œλΆ€ν„° μ°¨λ‘€λŒ€λ‘œ μ„ νƒν•˜κ³ 
이미 μ •λ ¬λœ λ°°μ—΄ λΆ€λΆ„κ³Ό 비ꡐ ν›„ μ•Œλ§žμ€ μœ„μΉ˜λ₯Ό μ°Ύμ•„ μ‚½μž…ν•¨μœΌλ‘œμ¨ 정렬을 μ™„μ„±ν•˜λŠ” μ•Œκ³ λ¦¬μ¦˜μ΄λ‹€.

# 2. λ™μž‘λ°©μ‹

key값을 μ •λ ¬λœ λ°°μ—΄ λΆ€λΆ„κ³Ό λΉ„κ΅ν•˜μ—¬ μ•Œλ§žμ€ μœ„μΉ˜μ— μ‚½μž…

μ‚½μž… μ „, xλŠ” μ •λ ¬λ˜μ§€ μ•Šμ€ λΆ€λΆ„μ˜ 첫번째 μš”μ†Œλ‘œ μ„ νƒλœ ν‚€ 값이닀.

μ‚½μž… ν›„, μ‚½μž… 된 λΆ€λΆ„μ—μ„œ xκ°€ λ“€μ–΄κ°ˆ μ•Œλ§žμ€ μœ„μΉ˜μ— μ‚½μž…ν•˜κ²Œ λœλ‹€.

μ •λ ¬λ˜μ§€ μ•Šμ€ ν•­λͺ© 쀑 첫번째 ν•­λͺ©μ΄ λ‹€μŒ keyκ°’μœΌλ‘œ μ§€μ •λœλ‹€.

# 3. νŠΉμ§•

# 1) μž₯점

  • κ°„λ‹¨ν•œ κ΅¬ν˜„
  • 같은 κ°’ μ‚¬μ΄μ—λŠ” μƒλŒ€μ  μœ„μΉ˜ λ³€ν™”κ°€ μ—†μŒ
  • Stableν•œ μ •λ ¬μž„
  • 주어진 μžλ£Œκ³΅κ°„ μ΄μ™Έμ˜ 곡간을 μ‚¬μš©ν•˜μ§€ μ•ŠμŒ

# 2) 단점

  • μž…λ ₯데이터 λ°°μ—΄μ˜ 길이가 κΈΈμ–΄μ§ˆμˆ˜λ‘ λΉ„νš¨μœ¨μ 
  • μ—­μœΌλ‘œ μ •λ ¬λ˜μ–΄ μžˆλŠ” μž…λ ₯ 값에 λŒ€ν•΄μ„œ μ΅œμ•…μ˜ μ„±λŠ₯을 λ³΄μž„ (λͺ¨λ“  μž…λ ₯ 값에 λŒ€ν•΄ μ‚½μž…μ΄ ν•„μš”)

# 4. μ‹œκ°„λ³΅μž‘λ„

T(n) = c1n+c2(nβˆ’1)+c4(nβˆ’1)+c5(n(n+1)/2βˆ’1)+c6(n(nβˆ’1)/2)+c7(n(nβˆ’1)/2)+c8(nβˆ’1)
                            
∴T(n)= O(n^2)

# 5. 예제 μ½”λ“œ

import java.util.Scanner;
// λ‹¨μˆœ μ‚½μž… μ •λ ¬

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;
		}
	}

	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]);
	}
}
Last Updated: 12/5/2020, 11:36:44 AM