Browse Source

Updated sorting.py with a better heap sort algorithm

luislopez66 2 years ago
parent
commit
d14d528dae
1 changed files with 9 additions and 10 deletions
  1. 9
    10
      sorting.py

+ 9
- 10
sorting.py View File

10
 from random import randint
10
 from random import randint
11
 import time
11
 import time
12
 from merge import merge
12
 from merge import merge
13
-from heapq import heapify
13
+import heapq
14
 
14
 
15
 # Python program for implementation of MergeSort
15
 # Python program for implementation of MergeSort
16
 
16
 
30
 	mergeSort(lista, m+1, r)
30
 	mergeSort(lista, m+1, r)
31
 	merge(lista, l, m, r)
31
 	merge(lista, l, m, r)
32
 
32
 
33
-def heapSort(lista):
33
+# Luis A. López Mañán
34
+# Code retreived from docs.python.org/3/library/heapq.html
35
+# October 11th, 2022
34
 
36
 
35
-	n = len(lista)
36
-	h1 = (n // 2) - 1
37
-	for i in range(h1, -1, -1):
38
-		heapify(lista[i])
37
+def heapSort(lista):
39
 
38
 
40
-	for i in range(n-1, -1, -1):
41
-		lista[i], lista[0] = lista[0], lista[i]
42
-		heapify(lista[i])
39
+	h = []
43
 
40
 
44
-	return lista
41
+	for val in lista:
42
+		heappush(h, val)
43
+	return [heappop(h) for i in range(len(h))]
45
 
44
 
46
 def quickSort(lista):
45
 def quickSort(lista):
47
 	#definan el algoritmo de ordenamiento quicksort
46
 	#definan el algoritmo de ordenamiento quicksort