repl.it
@pankajyd/

Implementing Min-Heap

C

No description

fork
loading
Files
  • main.c
main.c
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct Heap{
	int *A;
	int size;
}Heap;

void swap(Heap *H, int i, int j){
	int tmp;
	tmp = H->A[i];
	H->A[i] = H->A[j];
	H->A[j] = tmp;
}

void Heapify(Heap *H, int i){
	int min_index = i;
	
	if(2*i + 1 >= H->size){
		return;
	}
	else{
		if((H->A[i]) > (H->A[2*i + 1])){
			min_index = 2*i + 1;
		}
		if(2*i + 2 < H->size && H->A[2*i + 2] < H->A[min_index]){
			min_index = 2*i + 2;
		}
		if(min_index != i){
			swap(H, i, min_index);
			Heapify(H, min_index);
		}
	}
}

void Build_min_Heap(Heap *H){
	int n = H->size;
	for(int i = n/2; i >= 0; i--){
		Heapify(H, i);
	}
}

int Extract_min(Heap* H){
	int min = H->A[0];
	H->A[0] = H->A[H->size - 1];
	H->size--;
	Heapify(H, 0);
	return min;
}

void Decrease_key(Heap *H, int i, int key){
	H->A[i] = key;
	while(i >0 && H->A[i] < H->A[(i-1)/2]){
		H->A[i] = H->A[(i-1)/2];
		i = (i-1)/2;
	}
	H->A[i] = key;
}

int main(){
	int n ;
	scanf("%d", &n);

	Heap* H;
	int A[n];
	H->A = A;
	H->size = n;
	for(int i = 0; i < n; i++){
		scanf("%d", &A[i]);
	}
	
	Build_min_Heap(H);
	//Decrease_key(H, 2, 1);
	int min;
	for(int i = 0; i < n; i++){
		min = Extract_min(H);
		printf("(%d)", min);
	}
	return 0;
}