SHARE
TWEET

heapsort

michalkowalczyk Dec 3rd, 2018 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Nov 26 07:59:21 2018
  4.  
  5. @author: kowamich
  6. """
  7.  
  8. A=[]
  9. from random import randint
  10. for i in range(0,100):
  11.     j=randint(1,100)
  12.     A.append(j)
  13. print(A)
  14.  
  15. print()
  16.  
  17. def heapify(A,n,i):
  18.     largest = i
  19.     left = 2*i+1
  20.     right = 2*i+2
  21.    
  22.     if(left<n and A[i]<A[left]):
  23.         largest = left
  24.        
  25.     if(right<n and A[largest]<A[right]):
  26.         largest = right
  27.            
  28.     if(largest != i):
  29.         A[i],A[largest] = A[largest],A[i]
  30.        
  31.         heapify(A,n, largest)
  32.        
  33. def heapsort(A):
  34.     n = len(A)
  35.    
  36.     #budowanie kopca maksymalnego
  37.     for i in range(n,-1,-1):
  38.         heapify(A,n,i)
  39.        
  40.     for i in range(n-1,0,-1):
  41.         A[i],A[0] = A[0],A[i]
  42.        
  43.         heapify(A,i,0)
  44.        
  45. heapsort(A)
  46. print(A)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top