Browse Source

Update sorting.py by adding heap sort´s code

luislopez66 2 years ago
parent
commit
1d550b982b
1 changed files with 51 additions and 5 deletions
  1. 51
    5
      sorting.py

+ 51
- 5
sorting.py View File

@@ -9,12 +9,33 @@ Al final se imprimen los promedios de cada algortimo
9 9
 from random import randint
10 10
 import time
11 11
 from merge import merge
12
-import heapq
12
+import heapify # Se importa esa librería para usar heapify
13 13
 
14
-def mergeSort(lista):
15
-	#definan el algoritmo de ordenamiento mergesort
16
-	return lista
14
+'''
15
+ Python program for implementation of MergeSort  taken from https://www.geeksforgeeks.org/python-program-for-merge-sort/#:~:text=Merge%20Sort%20is%20a%20Divide,assumes%20that%20arr%5Bl..
16
+ Merges two subarrays of arr[].
17
+ First subarray is arr[l..m]
18
+ Second subarray is arr[m+1..r]
19
+'''
20
+
21
+
22
+def mergeSort(lista, l, r):
23
+	if l < r:
24
+		# Same as (l+r)//2, but avoids overflow for
25
+		# large l and h
26
+		m = l + (r - l) // 2
27
+
28
+		# Sort first and second halves
29
+		mergeSort(lista, l, m)
30
+		mergeSort(lista, m + 1, r)
31
+		merge(lista, l, m, r)
17 32
 
33
+""" Código tomado de GeeksForGeeks.
34
+	Enlace electrónico del código 
35
+ 	encontrado y adaptado para la
36
+  	asignación o el proyecto de prác-
37
+   	tica con git: https://www.geeksforgeeks.org/heap-sort/
38
+"""
18 39
 def heapSort(lista):
19 40
 	#definan el algoritmo de ordenamiento heapsort
20 41
 	heapq.heapify(lista)
@@ -42,8 +63,33 @@ def quickSort(lista):
42 63
 	#definan el algoritmo de ordenamiento quicksort
43 64
 	return lista
44 65
 
66
+
67
+''' 
68
+	This algorithm was taken from: https://www.programiz.com/dsa/shell-sort 
69
+	and was adapted in order to work for this assigment.
70
+'''
71
+
72
+
45 73
 def shellSort(lista):
46
-	#definan el algoritmo de ordenamiento shellsort
74
+	# Determine the list size to find the gap.
75
+	n = len(lista)
76
+	gap = n // 2
77
+
78
+	# this algorithm will run until gap reaches 1
79
+	while gap > 0:
80
+		for i in range(gap, n):
81
+			temp = lista[i]  # storing all items from lista into temp
82
+			j = i
83
+
84
+			# compares the number in temp with the 0th possition (start of list)
85
+			# if temp is larger than the first element then we swap them
86
+			while j >= gap and lista[j - gap] > temp:
87
+				lista[j] = lista[j - gap]
88
+				j -= gap
89
+
90
+			lista[j] = temp
91
+		gap = gap // 2  # decreases the gap to continue the loop
92
+
47 93
 	return lista
48 94
 
49 95
 maxValor=1000 	#define el valor maximo de los elementos de la lista