heapSort
Heap Sort
ํ์ ๋ ฌ (Heap Sort)
: ํํธ๋ฆฌ ๊ตฌ์กฐ (Heap Tree Structure) ๋ฅผ ์ด์ฉํ๋ ์ ๋ ฌ ๋ฐฉ๋ฒ ํ์ ์ด์งํธ๋ฆฌ (Binart Tree: ๋ฐ์ดํฐ๋ฅผ ๊ฐ ๋ ธ๋(node)์ ๋ด์ ๋ค์ ๋ ธ๋๋ฅผ ๋๊ฐ์ฉ ์ด์ด ๋ถ์ด๋ ๊ตฌ์กฐ)
์ ๋ ฌ ๋ฐฉ๋ฒ
n๊ฐ์ ๋ ธ๋์ ๋ํ ์์ ์ด์ง ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ๋ค. ์ด๋ ๋ฃจํธ ๋ ธ๋๋ถํฐ ๋ถ๋ชจ๋ ธ๋, ์ผ์ชฝ ์์๋ ธ๋, ์ค๋ฅธ์ชฝ ์์๋ ธ๋ ์์ผ๋ก ๊ตฌ์ฑํ๋ค.
์ต๋ ํ์ ๊ตฌ์ฑํ๋ค. ์ต๋ ํ์ด๋ ๋ถ๋ชจ๋ ธ๋๊ฐ ์์๋ ธ๋๋ณด๋ค ํฐ ํธ๋ฆฌ๋ฅผ ๋งํ๋๋ฐ, ๋จ๋ง ๋ ธ๋๋ฅผ ์์๋ ธ๋๋ก ๊ฐ์ง ๋ถ๋ชจ๋ ธ๋๋ถํฐ ๊ตฌ์ฑํ๋ฉฐ ์๋๋ถํฐ ๋ฃจํธ๊น์ง ์ฌ๋ผ์ค๋ฉฐ ์์ฐจ์ ์ผ๋ก ๋ง๋ค์ด ๊ฐ ์ ์๋ค.
๊ฐ์ฅ ํฐ ์(๋ฃจํธ์ ์์น)๋ฅผ ๊ฐ์ฅ ์์ ์์ ๊ตํํ๋ค.
2์ 3์ ๋ฐ๋ณตํ๋ค.

class HeapSort {
// ๋ฐฐ์ด ์์ a[idx1]๊ณผ a[idx2]์ ๊ฐ์ ๋ฐ๊ฟ๋๋ค.
static void swap(int[] a, int idx1, int idx2) {
int t = a[idx1];
a[idx1] = a[idx2];
a[idx2] = t;
}
// a[left] ~ a[right]๋ฅผ ํ์ผ๋ก ๋ง๋ญ๋๋ค.
// a[left] ์ด์ธ์๋ ๋ชจ๋ ํ์ํ๋ผ๊ณ ๊ฐ์ ํ๊ณ a[left]๋ฅผ ์๋ซ๋ถ๋ถ์ ์๋ง์ ์์น๋ก ์ฏ๊ฒจ ํ ์ํ๋ฅผ ๋ง๋ ๋ค
static void downHeap(int[] a, int left, int right) {
int temp = a[left]; // ๋ฃจํธ
int child; // ํฐ ๊ฐ์ ๊ฐ์ง ๋
ธ๋
int parent; // ๋ถ๋ชจ
for (parent = left; parent < (right + 1) / 2; parent = child) {
int cl = parent * 2 + 1; // ์ผ์ชฝ ์์
int cr = cl + 1; // ์ค๋ฅธ์ชฝ ์์
child = (cr <= right && a[cr] > a[cl]) ? cr : cl; // ํฐ ๊ฐ์ ๊ฐ์ง ๋
ธ๋๋ฅผ ์์์ ๋์
if (temp >= a[child])
break;
a[parent] = a[child];
}
a[parent] = temp;
}
// ํ ์ ๋ ฌ
// ์์์ ๊ฐ์๊ฐ n๊ฐ์ธ ๋ฐฐ์ด a๋ฅผ ํ ์ ๋ ฌํ๋ ๋ฉ์๋ ์ด๋ค
// downHeap๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฐ์ด a๋ฅผ ํ์ผ๋ก ๋ง๋ ๋ค
// ๋ฃจํธ(a[0]) ์ ์๋ ๊ฐ์ฅ ํฐ ๊ฐ์ ๋นผ๋ด์ด ๋ง์ง๋ง ์์์ ๋ฐ๊พธ๊ณ ๋ฐฐ์ด์ ๋๋จธ๋น ๋ถ๋ถ์ ๋ค์ ํ์ผ๋ก ๋ง๋๋ ๊ณผ์ ์ ๋ฐ๋ณตํ์ฌ ์ ๋ ฌ์ ์ํ
static void heapSort(int[] a, int n) {
for (int i = (n - 1) / 2; i >= 0; i--) // a[i] ~ a[n-1]๋ฅผ ํ์ผ๋ก ๋ง๋ค๊ธฐ
downHeap(a, i, n - 1);
for (int i = n - 1; i > 0; i--) {
swap(a, 0, i); // ๊ฐ์ฅ ํฐ ์์์ ์์ง ์ ๋ ฌ๋์ง ์์ ๋ถ๋ถ์ ๋ง์ง๋ง ์์๋ฅผ ๊ตํ
downHeap(a, 0, i - 1); // a[0] ~ a[i-1]์ ํ์ผ๋ก ๋ง๋ญ๋๋ค.
}
}
public static void main(String[] args) {
int[] x = { 1, 10, 5, 8, 7, 6, 4, 3, 2, 9 };
heapSort(x, 10); // ๋ฐฐ์ด x๋ฅผ ํต ์ ๋ ฌ
for (int i = 0; i < x.length; i++)
System.out.println("x[" + i + "]๏ผ" + x[i]);
}
}
Last updated
Was this helpful?