-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSC162_LAB14_SBK.py
80 lines (69 loc) · 2.2 KB
/
CSC162_LAB14_SBK.py
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
# sarah kingan
# CSC162, summer2015
# Lab 14
#
# Using the buildHeap method, write a sorting function
# that can sort a list in O(nlogn) time..
#
# some code modified from Problem Solving with Algorithms
# and Data Structures, By Brad Miller and David Ranum
#
# http://www.codeskulptor.org/#user40_ABSXhrex5U_2.py
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i * 2
else:
return i * 2 + 1
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0):
self.percDown(i)
i = i - 1
#####################################################
def BHSort(list):
bh = BinHeap()
bh.buildHeap(list)
sortedList = []
i = 0
while i < len(list):
sortedList.append(bh.delMin())
i = i + 1
return sortedList
#####################################################
a = [9,5,1,2,3,25,3,7,8,4,0,23,34]
print BHSort(a)