Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 이분 탐색
- 클래스
- BFS
- 비트마스크
- 우선순위 큐
- 중복 순열
- MST
- BeautifulSoup
- 크루스칼
- 그리디
- dfs
- 피보나치 수
- 분할 정복
- 순열
- Knapsack
- 조합
- 메모리풀
- SSAFY
- DP
- 세그먼트 트리
- 스택
- 큐
- 빠른 입출력
- 링크드리스트
- 재귀
- 문자열
- lis
- 백트래킹
- 완전 탐색
- 시뮬레이션
Archives
- Today
- Total
작심 24/7
6. 힙 정렬 (Heap Sort) 본문
#include <iostream>
using namespace std;
void heapify(int arr[], int N, int parent) {
int child1 = parent * 2 + 1, child2 = parent * 2 + 2;
int Max = parent, temp = 0;
if (child1 < N) {
if (arr[parent] < arr[child1])Max = child1;
}
if (child2 < N) {
if (arr[parent] < arr[child2]) {
if (arr[child1] < arr[child2]) {
Max = child2;
}
}
}
if (Max != parent) { //부모가 자식보다 더 작으면 교환한다
temp = arr[Max];
arr[Max] = arr[parent];
arr[parent] = temp;
heapify(arr, N, Max); //교환 후 그 자식의 자식과 다시 비교를 위해 재귀
}
}
void heapSort(int arr[], int last) { //힙 정렬
for (int i = N - 1; i >= 0; i--) {
//루트와 마지막 노드를 교환한다
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapify(arr, i, 0); //마지막 노드를 제외한 뒤 루트를 기준으로 heapify 시킨다
}
}
int main() {
int arr[6] = {1, 12, 9, 5, 6, 10};
int N = 6;
for (int i = (N - 1) / 2; i >= 0; i--) heapify(arr, N, i); //초기 최대 힙 구조로 만든다
heapSort(arr, N); //최대 힙이므로 오름차순 정렬
for (int i = 0; i < N; i++) cout << arr[i] << "\n";
return 0;
}
'개념' 카테고리의 다른 글
비트마스크 (BitMask) (0) | 2021.08.07 |
---|---|
7. 계수 정렬 (Counting Sort) (2) | 2020.05.22 |
5. 합병 정렬 (Merge Sort) (0) | 2020.05.20 |
4. 퀵 정렬 (Quick Sort) (0) | 2020.05.20 |
3. 삽입 정렬 (Insertion Sort) (0) | 2020.05.20 |
Comments