-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpriqueue.cpp
More file actions
77 lines (69 loc) · 1.4 KB
/
Copy pathpriqueue.cpp
File metadata and controls
77 lines (69 loc) · 1.4 KB
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
/* Copyright (C) 1999 Lucent Technologies */
/* From 'Programming Pearls' by Jon Bentley */
/* priqueue.cpp -- priority queues (using heaps) */
#include <iostream>
using namespace std;
// define and implement priority queues
template<class T>
class priqueue {
private:
int n, maxsize;
T *x;
void swap(int i, int j)
{ T t = x[i]; x[i] = x[j]; x[j] = t; }
public:
priqueue(int m)
{ maxsize = m;
x = new T[maxsize+1];
n = 0;
}
void insert(T t)
{ int i, p;
x[++n] = t;
for (i = n; i > 1 && x[p=i/2] > x[i]; i = p)
swap(p, i);
}
T extractmin()
{ int i, c;
T t = x[1];
x[1] = x[n--];
for (i = 1; (c=2*i) <= n; i = c) {
if (c+1<=n && x[c+1]<x[c])
c++;
if (x[i] <= x[c])
break;
swap(c, i);
}
return t;
}
};
// sort with priority queues (heap sort is strictly better)
template<class T>
void pqsort(T v[], int n)
{ priqueue<T> pq(n);
int i;
for (i = 0; i < n; i++)
pq.insert(v[i]);
for (i = 0; i < n; i++)
v[i] = pq.extractmin();
}
// main
int main()
{ const int n = 10;
int i, v[n];
if (0) { // Generate and sort
for (i = 0; i < n; i++)
v[i] = n-i;
pqsort(v, n);
for (i = 0; i < n; i++)
cout << v[i] << "\n";
} else { // Insert integers; extract with 0
priqueue<int> pq(100);
while (cin >> i)
if (i == 0)
cout << pq.extractmin() << "\n";
else
pq.insert(i);
}
return 0;
}