瀏覽代碼

update sorting.py again

luislopez66 2 年之前
父節點
當前提交
9c1ad1e57a
共有 1 個檔案被更改,包括 48 行新增11 行删除
  1. 48
    11
      sorting.py

+ 48
- 11
sorting.py 查看文件

@@ -30,25 +30,62 @@ def mergeSort(lista, l, r):
30 30
 	mergeSort(lista, m+1, r)
31 31
 	merge(lista, l, m, r)
32 32
 
33
-# Luis A. López Mañán
34
-# Code retreived from docs.python.org/3/library/heapq.html
35
-# October 11th, 2022
33
+''' Luis Andrés López Mañán
34
+    Program written by hand as a draft on 09/19/2022
35
+    Credit goes to GeeksForGeeks
36
+    Link: https://www.geeksforgeeks.org/python-program-for-heap-sort/
37
+    Last access on 09/19/2022
38
+    Program wrriten and edited on 10/10/2022
39
+'''
40
+
41
+# This function heapifies a subtree rooted at an index
42
+# i. Also, n is the size of a heap and arr is array.
43
+
44
+def heapify(lista, n, i):
45
+
46
+		# largest is root for now
47
+		largest = i
48
+
49
+		# left child of root
50
+		l = 2 * i + 1
51
+
52
+		# right child of root
53
+		r = 2 * i + 2
54
+
55
+		# Checks if root has a left child and is greater than root
56
+		if l < n and lista[i] < lista[l] :
57
+			largest = l
58
+
59
+		# Checks if root has a right child and is greater than root
60
+		if r < n and lista[largest] < lista[r]:
61
+			largest = r
62
+
63
+		# If necessary, this changes root by swapping values
64
+    	if largest != i:
65
+        	lista[i], lista[largest] = lista[largest], lista[i]
66
+
67
+		# This heapifies the root repeatedly
68
+		heapify(lista, n, largest)
36 69
 
37 70
 def heapSort(lista):
38 71
 
39
-	h = []
72
+		n = len(lista)
73
+		for i in range((n // 2) - 1, -1, -1):
74
+			heapify(lista, n, i)
75
+
76
+		for i in range(n-1, -1, -1):
77
+			lista[i], lista[0] = lista[0], lista[i]
78
+			heapify(lista, i, 0)
40 79
 
41
-	for val in lista:
42
-		heappush(h, val)
43
-	return [heappop(h) for i in range(len(h))]
80
+		return lista
44 81
 
45 82
 def quickSort(lista):
46
-	#definan el algoritmo de ordenamiento quicksort
47
-	return lista
83
+		#definan el algoritmo de ordenamiento quicksort
84
+		return lista
48 85
 
49 86
 def shellSort(lista):
50
-	#definan el algoritmo de ordenamiento shellsort
51
-	return lista
87
+		#definan el algoritmo de ordenamiento shellsort
88
+		return lista
52 89
 
53 90
 maxValor=1000 	#define el valor maximo de los elementos de la lista
54 91
 largoLista=1000 	#define el largo de las listas a ordenar