-
-
Save Rag0n/10548899 to your computer and use it in GitHub Desktop.
Binary heap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
int heap[1000000]; | |
int size = 0; | |
int StrCompare(char *Str1,char *Str2) | |
{ | |
while(*Str1==*Str2 && *Str1!=0) | |
{ | |
Str1++; | |
Str2++; | |
} | |
return *Str1-*Str2; | |
} | |
void swap(int one, int two) | |
{ | |
int temp = heap[one]; | |
heap[one] = heap[two]; | |
heap[two] = temp; | |
} | |
void heapify(int pos) | |
{ | |
int left = pos*2 + 1, right = pos*2 + 2; | |
int largest = pos; | |
if (left < size && heap[left] > heap[largest]) | |
{ | |
largest = left; | |
} | |
if (right < size && heap[right] > heap[largest]) | |
{ | |
largest = right; | |
} | |
if (largest != pos) | |
{ | |
swap(pos, largest); | |
heapify(largest); | |
} | |
} | |
void insert(int value) | |
{ | |
int pos = size, parent; | |
heap[size] = value; | |
size++; | |
while(pos) | |
{ | |
parent = (pos-1)/2; | |
if (heap[pos] > heap[parent]) | |
{ | |
swap(pos, parent); | |
pos = (pos-1)/2; | |
} | |
else | |
break; | |
} | |
} | |
int pop() | |
{ | |
int num = heap[0]; | |
swap(0, size-1); | |
size--; | |
heapify(0); | |
printf("%d\n", num); | |
return 0; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char input[8]; | |
int num, count; | |
char Extract[]= "Extract"; | |
char Insert[]= "Insert"; | |
scanf("%d", &count); | |
for (int i = 0; i < count; ++i) | |
{ | |
scanf("%s", input); | |
if (StrCompare(input, Insert) == 0) | |
{ | |
scanf("%d", &num); | |
insert(num); | |
} | |
else if (StrCompare(input, Extract) == 0) | |
{ | |
pop(); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment