"C언어 우선순위큐 구현"의 두 판 사이의 차이

잔글 (Jmnote님이 C언어 우선순위 큐 구현 문서를 C언어 우선순위큐 구현 문서로 이동하면서 넘겨주기를 덮어썼습니다)
 
(같은 사용자의 중간 판 3개는 보이지 않습니다)
62번째 줄: 62번째 줄:


int main() {
int main() {
    push(7);
     push(5);
     push(5);
     push(3);
     push(3);
     push(9);
     push(9);
     push(0);
     push(5);
    push(1);
     while (!empty()) {
     while (!empty()) {
         printf("%d ", pop());  // 0 3 5 9
         printf("%d ", pop());  // 1 3 5 5 7 9  
     }
     }
     pop(); // empty!!!
     pop(); // empty!!!
}
}
</syntaxhighlight>
</syntaxhighlight>
75번째 줄: 77번째 줄:
==같이 보기==
==같이 보기==
* [[C언어 큐 구현]]
* [[C언어 큐 구현]]
* [[C언어 해시 테이블 구현]]
* [[C++ 우선순위 큐]]
* [[C++ 우선순위 큐]]


[[분류: C]]
[[분류: C]]
[[분류: 우선순위 큐]]
[[분류: 우선순위 큐]]

2024년 2월 3일 (토) 19:10 기준 최신판

1 개요[ | ]

C언어 우선순위큐 구현
#include <stdio.h>

#define MAX_N 100

int heap[MAX_N];
int heapSize = 0;

void clear() {
    heapSize = 0;
}

int empty() {
    return heapSize == 0;
}

void push(int value) {
    if (heapSize + 1 > MAX_N) {
        printf("overflow!!!");
        return;
    }
    heap[heapSize] = value;
    int current = heapSize;
    while (current > 0 && heap[current] < heap[(current - 1) / 2]) {
        int temp = heap[(current - 1) / 2];
        heap[(current - 1) / 2] = heap[current];
        heap[current] = temp;
        current = (current - 1) / 2;
    }
    heapSize += 1;
}

int pop() {
    if (heapSize <= 0) {
        printf("empty!!!");
        return 0;
    }
    int value = heap[0];
    heapSize -= 1;
    heap[0] = heap[heapSize];
    int current = 0;
    while (current * 2 + 1 < heapSize) {
        int child;
        if (current * 2 + 2 == heapSize) {
            child = current * 2 + 1;
        } else {
            child = heap[current * 2 + 1] < heap[current * 2 + 2]
                        ? current * 2 + 1
                        : current * 2 + 2;
        }
        if (heap[current] < heap[child]) break;
        int temp = heap[current];
        heap[current] = heap[child];
        heap[child] = temp;
        current = child;
    }
    return value;
}

int main() {
    push(7);
    push(5);
    push(3);
    push(9);
    push(5);
    push(1);
    while (!empty()) {
        printf("%d ", pop());  // 1 3 5 5 7 9 
    }
    pop(); // empty!!!
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}