Hsue66 / Algo

0 stars 0 forks source link

heap #12

Open Hsue66 opened 4 years ago

Hsue66 commented 4 years ago

/*#include using namespace std;

define MAX 100

struct minHeap { int heap[MAX]; int size;

void init() {
    size = 0;
}

void push(int data) {
    int target = size + 1;
    while (target != 1 && heap[target / 2] > data) {
        heap[target] = heap[target / 2];
        target /= 2;
    }
    heap[target] = data;
    size++;
}

int top() {
    return heap[1];
}

void pop() {
    int parent = 1, child = 2;
    int temp = heap[size];
    while (child < size) {
        if (child + 1 < size && heap[child + 1] < heap[child])
            child++;
        if (heap[child] >= temp) break;
        heap[parent] = heap[child];
        parent = child;
        child += 2;
    }
    heap[parent] = temp;
    size--;
}

void show() {
    for (int i = 1; i <= size; i++)
        cout << heap[i] << " ";
    cout << endl;
}

};

int main() { minHeap minheap; minheap.init(); minheap.push(2); minheap.push(4); minheap.push(3); minheap.push(1); minheap.push(8); minheap.show();

for (int i = 0; i < 5; i++) {
    cout << minheap.top() << " ";
    minheap.pop();
}

}*/