728x90
1. HeapSort
struct heap{
keytype S[1...n];
int heapsize;
}
void siftdown(heap& H, index i){
index parent, largerchild;
keytype siftkey;
bool spotfound;
parent=i;
siftkey=H.S[i];
spotfound=false;
while(2*parent<=H.heapsize && !spotfound){
if(2*parent<=heapsize && H.S[2*parent+1]<=H.S[2*parent]){
largerchild=2*parent;
}else{
largerchild=2*parent+1;
}
if(siftkey<H.S[largerchild]){
H.S[parent]=H.S[largerchild];
parent=largerchild;
}else{
spotfound=true;
}
}
H.S[parent]=siftkey;
}
keytype root(heap& H){
keytype keyout;
keyout=H.S[H.heapsize];
i=H.heapsize;
H.S[1]=H.S[H.heapsize];
H.heapsize=H.heapsize-1;
siftdown(H,1);
return keyout;
}
void removekeys(int n, heap& H, keytype S[]){
index i;
for(i=n;i>=1;i--){
S[i]=root(H);
}
}
void makeheap(int n, heap& H){
index i;
for(i=n/2;i>=1;i--){
siftdown(H,i);
}
}
void heapsort(int n, heap& H){
makeheap(n,H);
removekeys(n,H,H.S);
}
728x90
'알고리즘' 카테고리의 다른 글
[알고리즘]순열, 조합, 부분집합 - Java로 구현하기 (1) | 2024.02.24 |
---|---|
[알고리즘]DynamicProgramming (0) | 2022.04.23 |
[알고리즘]Sorting Algorithm_RadixSort (0) | 2022.04.23 |
[알고리즘]동적 계획법 (0) | 2021.01.18 |
[알고리즘]깊이/너비 우선 탐색 (0) | 2021.01.16 |