heap sort algorithm in python

Solutions on MaxInterview for heap sort algorithm in python by the best coders in the world

showing results for - "heap sort algorithm in python"
Alejandro
28 Oct 2020
1def buildHeap(lista, n):
2    for i in range(n//2 - 1, -1, -1):
3        heapify(lista, n, i)
4
5def heapify(lista, n, i):
6    largest = i  
7    left = (2 * i) + 1    
8    right = (2 * i) + 2 
9
10    if left < n and lista[largest] < lista[left]:
11        largest = left
12
13    if right < n and lista[largest] < lista[right]:
14        largest = right
15
16    if largest != i:
17        lista[i], lista[largest] = lista[largest], lista[i] 
18        heapify(lista, n, largest) 
19
20def heapSort(lista):
21    n = len(lista)
22    buildHeap(lista, n)
23    
24    for i in range(n-1, 0, -1):
25        lista[i], lista[0] = lista[0], lista[i]
26        heapify(lista, i, 0)
Felix
14 Mar 2019
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4Created on Sun Mar 10 18:18:25 2019
5
6@source: https://www.geeksforgeeks.org/heap-sort/
7
8"""
9# Python program for implementation of heap Sort 
10
11# To heapify subtree rooted at index i. 
12# n is size of heap 
13def heapify(arr, n, i): 
14	largest = i # Initialize largest as root 
15	l = 2 * i + 1	 # left = 2*i + 1 
16	r = 2 * i + 2	 # right = 2*i + 2 
17
18	# See if left child of root exists and is 
19	# greater than root 
20	if l < n and arr[i] < arr[l]: 
21		largest = l 
22
23	# See if right child of root exists and is 
24	# greater than root 
25	if r < n and arr[largest] < arr[r]: 
26		largest = r 
27
28	# Change root, if needed 
29	if largest != i: 
30		arr[i],arr[largest] = arr[largest],arr[i] # swap 
31
32		# Heapify the root. 
33		heapify(arr, n, largest) 
34
35# The main function to sort an array of given size 
36def heapSort(arr): 
37	n = len(arr) 
38
39	# Build a maxheap. 
40	for i in range(n, -1, -1): 
41		heapify(arr, n, i) 
42
43	# One by one extract elements 
44	for i in range(n-1, 0, -1): 
45		arr[i], arr[0] = arr[0], arr[i] # swap 
46		heapify(arr, i, 0) 
47
48heapSort(arr) 
49 
50