ํ”„๋กœ๊ทธ๋ž˜๋ฐ/Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ์„ ํƒ ์ •๋ ฌ Selection Sort

NaNaRin๐Ÿ™ƒ 2021. 1. 24. 16:14

 

์„ ํƒ ์ •๋ ฌ (Selection Sort) ์•Œ๊ณ ๋ฆฌ์ฆ˜ :

๊ฐ€์žฅ ์ž‘์€ ์š”์†Œ๋ถ€ํ„ฐ ์„ ํƒํ•ด ์•Œ๋งž์€ ์œ„์น˜๋กœ ์˜ฎ๊ฒจ์„œ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

1. ์•„์ง ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๋ถ€๋ถ„์—์„œ ๊ฐ€์žฅ ์ž‘์€ ์š”์†Œ selection[i]๋ฅผ ์„ ํƒ

2. selection[i]์™€ ์•„์ง ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๋ถ€๋ถ„์˜ ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๊ตํ™˜

3. n-1ํšŒ ๋ฐ˜๋ณต

 

๋ฐฐ์—ด selection์˜ ์„ ํƒ ์ •๋ ฌ ๊ณผ์ •

 

๋ฉ”์„œ๋“œ swap() : a[idx1] ๊ณผ a[idx2] ๋ฅผ ๊ตํ™˜

๋งค๊ฐœ๋ณ€์ˆ˜ : int[] a, int idx1, int idx2

 

๋ฉ”์„œ๋“œ selectionSort() : ๊ธธ์ด๊ฐ€ n์ธ ๋ฐฐ์—ด a๋ฅผ ์„ ํƒ ์ •๋ ฌ

๋งค๊ฐœ๋ณ€์ˆ˜ : int[] a, int n

 

- ์„ ํƒ ์ •๋ ฌ

void swap(int[] a, int idx1, int idx2) {
	int t = a[idx1];
	a[idx1] = a[idx2];
	a[idx2] = t;
}

void selectionSort(int[] a, int n) {
	for(int i = 0; i < n-1; i++) {
		int min = i;
		for(int j = i+1; j < n; j++) {
			if(a[j] < a[min]) {
				min = j;
			}
		}
		swap(a, i, min);
	}
}

 

 

 

 

์„ ํƒ ์ •๋ ฌ Selection Sort :

์ตœ์„  = ํ‰๊ท  = ์ตœ์•… = O(N^2)

๋ถˆ์•ˆ์ •ํ•œ ์ •๋ ฌ