티스토리 뷰
자료구조인 힙(heap)을 이용한 정렬 알고리즘
- Heap을 구성한 후 원소들을 다 삽입하고 하나씩 빼면서 배열의 앞에서부터 채워넣는다.
#define N 6
int data[N] = {40, 6, 1, 9, 3, 5};
int h[N + 5];
int cnt;
heapSort(0, N - 1);
void swap(int i, int j)
{
int t = h[i];
h[i] = h[j];
h[j] = t;
}
void upHeapify(int index)
{
if (index == 1)
return;
if (h[index] < h[index / 2])
{
swap(index, index / 2);
upHeapify(index / 2);
}
}
void insert(int data)
{
h[++cnt] = data;
upHeapify(cnt);
}
void downHeapify(int index)
{
int temp;
if (index * 2 > cnt)
return;
if (index * 2 + 1 <= cnt)
{
if (j[index * 2] < h[index * 2 + 1])
temp = index * 2;
else
temp = index * 2 + 1;
}
else
temp = index * 2;
if (h[temp] < h[index])
{
swap(index, temp);
downHeapify(temp);
}
}
void pop(void)
{
h[1] = h[cnt--];
downHeapify(1);
}
int top(void)
{
return h[1];
}
void heapSort(int st, int ed)
{
int i;
for (i = st; i <= ed; i++)
insert(data[i]);
for (i = st; i <= ed; i++)
{
data[i] = top();
pop();
}
}
- 시간복잡도 : O(Nlog(N))
- 공간복잡도 : O(Nlog(N))
'공부 > SW Professional' 카테고리의 다른 글
[알고리즘] 기수 정렬(radix sort) (0) | 2021.05.25 |
---|---|
[알고리즘] 계수 정렬(counting sort) (0) | 2021.05.25 |
[알고리즘] 퀵 정렬(quick sort) (0) | 2021.05.25 |
[알고리즘] 합병 정렬(merge sort) (0) | 2021.05.25 |
[알고리즘] 삽입 정렬(insertion sort) (0) | 2021.05.25 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크