nikbel

heap_sort

Mar 18th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. with open('sort.txt') as f:
  2.     for lines in f:
  3.         lines = [int(x) for x in lines.split(',')]
  4. arr = lines
  5.  
  6. def add(x):
  7.     nonlocal heap
  8.     nonlocal hs
  9.     hs += 1
  10.     heap.append(x)
  11.     siftUp(hs)
  12.        
  13. def siftUp(i):
  14.     nonlocal heap
  15.     if len(heap) < 2: return
  16.     if heap[i] < heap[i//2]:
  17.         heap[i], heap[i//2] = heap[i//2], heap[i]
  18.         siftUp(i//2)
  19.            
  20. def siftDown(i):
  21.     nonlocal heap
  22.     nonlocal hs
  23.     s = i
  24.     if ((i*2 + 1) < hs and heap[i*2 + 1] < heap[s]): s = i*2 + 1
  25.     if ((i*2 + 2) < hs and heap[i*2 + 2] < heap[s]): s = i*2 + 2
  26.     if s != i:
  27.         heap[i], heap[s] = heap[s], heap[i]
  28.         siftDown(s)
  29.    
  30. heap = []
  31. hs = -1
  32.    
  33. for temp in arr:
  34.     add(temp)
  35.    
  36. result = []
  37.    
  38. for temp in range(hs, 0, -1):
  39.     result.append(heap[0])
  40.     heap[0] = heap.pop(temp)
  41.     hs -= 1
  42.     siftDown(0)
  43.    
  44. result += heap  
  45.    
  46. add(arr)  
  47. print (result)
  48. input()
Add Comment
Please, Sign In to add comment