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

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ํ€ต ์ •๋ ฌ Quick Sort

NaNaRin๐Ÿ™ƒ 2021. 1. 26. 22:10

 

ํ€ต ์ •๋ ฌ (Quick Sort) ์•Œ๊ณ ๋ฆฌ์ฆ˜ :

๋ถ„ํ•  ์ •๋ณต ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ค‘์˜ ํ•˜๋‚˜๋กœ, ๋งค์šฐ ๋น ๋ฅธ ์†๋„๋ฅผ ์ž๋ž‘ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

1. ๋ฐฐ์—ด ์•ˆ์˜ ํ•œ ์š”์†Œ๋ฅผ ์„ ํƒํ•˜์—ฌ ์ด๋ฅผ ํ”ผ๋ฒ—์ด๋ผ ํ•˜๊ณ , ๋ฐฐ์—ด์˜ ๋งจ ์ฒซ๋ฒˆ์งธ ์š”์†Œ์™€ ๊ตํ™˜

2. ๋ฐฐ์—ด์˜ ์™ผ์ชฝ ๋์—์„œ๋ถ€ํ„ฐ ํ”ผ๋ฒ—๋ณด๋‹ค ํฐ ์š”์†Œ๋ฅผ, ์˜ค๋ฅธ์ชฝ ๋์—์„œ๋ถ€ํ„ฐ ํ”ผ๋ฒ—๋ณด๋‹ค ์ž‘์€ ์š”์†Œ๋ฅผ ํƒ์ƒ‰

3. ์™ผ์ชฝ์—์„œ ๋ฐœ๊ฒฌํ•œ ํ”ผ๋ฒ—๋ณด๋‹ค ํฐ ์š”์†Œ์™€ ์˜ค๋ฅธ์ชฝ์—์„œ ๋ฐœ๊ฒฌํ•œ ํ”ผ๋ฒ—๋ณด๋‹ค ์ž‘์€ ์š”์†Œ๋ฅผ ๊ตํ™˜

3. ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ์—์„œ ํƒ์ƒ‰ํ•˜๋˜ ์ปค์„œ๊ฐ€ ๋งŒ๋‚˜๋ฉด ์ค‘์ง€, ํ”ผ๋ฒ—๊ณผ ๊ตํ™˜

    => ๋‘ ์ปค์„œ๊ฐ€ ๋งŒ๋‚œ ์œ„์น˜ ์™ผ์ชฝ์—๋Š” ํ”ผ๋ฒ—๋ณด๋‹ค ์ž‘์€ ์š”์†Œ๊ฐ€, ์˜ค๋ฅธ์ชฝ์—๋Š” ํฐ ์š”์†Œ๊ฐ€ ์œ„์น˜ํ•˜๊ฒŒ ๋œ๋‹ค

4. ํ”ผ๋ฒ—์„ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ๊ทธ๋ฃน๊ณผ ์˜ค๋ฅธ์ชฝ ๊ทธ๋ฃน์„ ๊ฐ๊ฐ ๋‹ค์‹œ ํ€ต ์ •๋ ฌ

5. ๊ฐ ๊ทธ๋ฃน์ด ๋”์ด์ƒ ๋ถ„ํ• ์ด ๋ถˆ๊ฐ€๋Šฅํ•  ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณต -> ๊ทธ๋ฃน ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ 0์ด๋‚˜ 1์ด๋ฉด ์ค‘์ง€

 

 

int[] quick = {5, 1, 4, 3, 7, 6, 2}

1. quick ๋ฐฐ์—ด์˜ ์ • ๊ฐ€์šด๋ฐ ์š”์†Œ๋ฅผ ํ”ผ๋ฒ—์œผ๋กœ ์ •ํ•˜๊ณ  ๋ฐฐ์—ด์˜ ๋งจ ์•ž ์š”์†Œ์™€ ๊ตํ™˜

2. ๋งจ ์™ผ์ชฝ๋ถ€ํ„ฐ L์ปค์„œ๊ฐ€ ํ”ผ๋ฒ—๋ณด๋‹ค ํฐ ๊ฐ’์„ ํƒ์ƒ‰, 4 ๋ฐœ๊ฒฌ / ๋งจ ์˜ค๋ฅธ์ชฝ๋ถ€ํ„ฐ R ์ปค์„œ๊ฐ€ ํ”ผ๋ฒ—๋ณด๋‹ค ์ž‘์€ ๊ฐ’์„ ํƒ์ƒ‰, 2 ๋ฐœ๊ฒฌ / ๋‘ ๊ฐ’ ๊ตํ™˜

3. L์ปค์„œ๊ฐ€ 5๋ฅผ ์ฐพ๊ณ  R์ปค์„œ๊ฐ€ 2๋ฅผ ์ฐพ์•˜์ง€๋งŒ, R์ปค์„œ๊ฐ€ L์ปค์„œ๋ณด๋‹ค ์™ผ์ชฝ์— ์œ„์น˜

4. ํ”ผ๋ฒ—๊ณผ R์ปค์„œ ์œ„์น˜์˜ ์š”์†Œ ๊ตํ™˜

5. ํ”ผ๋ฒ— 3์„ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ๊ทธ๋ฃน๊ณผ ์˜ค๋ฅธ์ชฝ ๊ทธ๋ฃน์„ ๊ฐ๊ฐ ํ€ต ์ •๋ ฌ

 

๋ฐฐ์—ด quick์˜ ํ€ต ์ •๋ ฌ ๊ณผ์ •

 

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

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

 

๋ฉ”์„œ๋“œ partition() : ๋ฐฐ์—ด a์˜ index left ๋ถ€ํ„ฐ right ๊นŒ์ง€ ์š”์†Œ ์ค‘ ํ”ผ๋ฒ—์„ ์ •ํ•ด ํ€ต ์ •๋ ฌ ํ›„ ํ”ผ๋ฒ— index ๋ฐ˜ํ™˜

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

๋ฐ˜ํ™˜๊ฐ’ : ํ€ต ์ •๋ ฌ ํ›„ ํ”ผ๋ฒ—์˜ index

 

๋ฉ”์„œ๋“œ quickSort() : ๋ฐฐ์—ด a์˜ index left ๋ถ€ํ„ฐ right ๊นŒ์ง€ ์š”์†Œ๋ฅผ ํ€ต ์ •๋ ฌ

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

 

- ํ€ต ์ •๋ ฌ : 

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

int partition(int[] a, int left, int right) {
	int pc = (left + right)/2;
	int pivot = a[pc];
	int pl = left;
	int pr = right;
	swap(a, pl, pc);
	
	while(pl < pr) {
		while(a[pr] > pivot) pr--;
		while(a[pl] <= pivot && pl < pr) pl++;
		swap(a, pl, pr);
	}
	a[left] = a[pl];
	a[pl] = pivot;
	return pl;
}
	
void quickSort(int[] a, int left, int right) {
	if(left >= right)
		return;
	
	int pc = partition(a, left, right);
	quickSort(a, left, pc-1);
	quickSort(a, pc+1, right);	
}

 

 

 

 

ํ€ต ์ •๋ ฌ Quick Sort :

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

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