Brak opisu

sorting.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """
  2. Carlos J Corrada Bravo
  3. Este programa calcula el promedio de tiempo de ejecucion de cuatro algoritmos de ordenamiento
  4. La variable maxValor define el valor maximo de los elementos de la lista
  5. La variable largoLista define el largo de las listas a ordenar
  6. La variable veces define las veces que se va a hacer el ordenamiento
  7. Al final se imprimen los promedios de cada algortimo
  8. """
  9. from random import randint
  10. import time
  11. import utils.qsortUtils as qsortUtils
  12. import math
  13. def mergeSort(lista):
  14. #definan el algoritmo de ordenamiento mergesort
  15. # If the size of the list is greater than 1 then it enters here
  16. if len(lista) > 1:
  17. # Gets the half of the list
  18. Midd = len(lista) // 2
  19. # Takes only the elements that are in the left of the list
  20. Left = lista[Midd:]
  21. # If the size of left still is not 1 then
  22. if len(Left) != 1:
  23. # it will do a recursive call to the function again
  24. mergeSort(Left)
  25. # Takes only the elements that are in the right of the list
  26. Right = lista[:Midd]
  27. # If the size of right still is not 1 then
  28. if len(Right) != 1:
  29. # it will do a recursive call to the function again
  30. mergeSort(Right)
  31. # Variables define for while and getting space in the list
  32. i = j = k = 0
  33. # While i and j are less than the comparation it enters here
  34. while i < len(Left) and j < len(Right):
  35. # If the compared number in i is less than j it enters here
  36. if Left[i] < Right[j]:
  37. # The less variable is stored in the list again in order
  38. lista[k] = Left[i]
  39. i += 1 # Increments i
  40. # If the compared number in i is greater than j it enters here
  41. else:
  42. # The less variable is stored in the list again in order
  43. lista[k] = Right[j]
  44. j += 1 # Increments j
  45. k += 1 # Increments k
  46. # If there are elements remaining in Left the they are put here
  47. while i < len(Left):
  48. # The variable that was remaining is put here
  49. lista[k] = Left[i]
  50. i += 1 # Increments i
  51. k += 1 # Increments k
  52. # If there are elements remaining in Right the they are put here
  53. while j < len(Right):
  54. # The variable that was remaining is put here
  55. lista[k] = Right[j]
  56. j += 1 # Increments j
  57. k += 1 # Increments k
  58. return lista
  59. # Code was base and taken from GeeksforGeeks
  60. def MAX_HEAPIFY(lista, index):
  61. # funcion para mantener la propiedad lista[PARENT(i)] >= lista[i]
  62. # para todo nodo excepto la raiz en el heap
  63. lefti = 2 * index + 1 # index hijo izquierdo
  64. righti = 2 * index + 2 # index hijo derecho
  65. largo = len(lista) - 1
  66. # Si el hijo izq es mayor que el padre
  67. if lefti <= largo and lista[lefti] > lista[index]:
  68. largest = lefti
  69. else:
  70. largest = index
  71. # Si el hijo derecho es mayor que el padre
  72. if righti <= largo and lista[righti] > lista[largest]:
  73. largest = righti
  74. # Si el index seleccionado no es el del numero mas grande
  75. if largest != index:
  76. # swap de los numeros en los indexes
  77. lista[index], lista[largest] = lista[largest], lista[index]
  78. MAX_HEAPIFY(lista, largest)
  79. def BUILD_MAX_HEAP(lista):
  80. largo = len(lista) - 1
  81. index = math.floor(largo/2)
  82. while index >= 1:
  83. MAX_HEAPIFY(lista,index)
  84. index = index - 1
  85. def heapSort(lista):
  86. #definan el algoritmo de ordenamiento heapsort
  87. BUILD_MAX_HEAP(lista)
  88. largo = len(lista)
  89. while largo >= 2:
  90. # swap del primer numero y el ultimo
  91. lista[0], lista[largo-1] = lista[largo-1], lista[0]
  92. largo = largo - 1
  93. MAX_HEAPIFY(lista,0)
  94. return lista
  95. def quickSort(lista):
  96. # Se aplica quicksort a la lista desde el primer elemento hasta el último
  97. qsortUtils.qSort(lista, 0, len(lista) - 1)
  98. return lista
  99. def shellSort(lista):
  100. #definan el algoritmo de ordenamiento shellsort
  101. Size = len(lista) # Contains the complete size of the list
  102. Diff = Size//2 # Contains the number of half of the list
  103. # Does a insertion sort by ordering in base of the Diff.
  104. while Diff > 0:
  105. # Begins a loop to sort the elements added to sorted array.
  106. for i in range(Diff, Size):
  107. # Saves the element sorted in a temporary variable
  108. Tmp = lista[i]
  109. j = i # Shifts the location of the elements
  110. # Looks for the locations
  111. while j >= Diff and lista[j - Diff] > Tmp:
  112. # Gives the new element to the location
  113. lista[j] = lista[j - Diff]
  114. # The size of the array is ajusted
  115. j -= Diff
  116. # Puts the Tmp variable in is correct location
  117. lista[j] = Tmp
  118. # Reduces again the list
  119. Diff //= 2
  120. return lista
  121. # Code was taken from GeeksforGeeks
  122. def main():
  123. maxValor=1000 #define el valor maximo de los elementos de la lista
  124. largoLista=1000 #define el largo de las listas a ordenar
  125. veces=100 #define las veces que se va a hacer el ordenamiento
  126. acumulaMerge=0 #variable para acumular el tiempo de ejecucion del mergesort
  127. acumulaHeap=0 #variable para acumular el tiempo de ejecucion del heapsort
  128. acumulaQuick=0 #variable para acumular el tiempo de ejecucion del quicksort
  129. acumulaShell=0 #variable para acumular el tiempo de ejecucion del shellsort
  130. for i in range(veces):
  131. mergelista = [randint(0,maxValor) for r in range(largoLista)] #creamos una lista con valores al azar
  132. heaplista=list(mergelista)
  133. quicklista=list(mergelista)
  134. searchlista=list(mergelista)
  135. t1 = time.perf_counter() #seteamos el tiempo al empezar
  136. mergeSort(mergelista) #ejecutamos el algoritmo mergeSort
  137. acumulaMerge+=time.perf_counter()-t1 #acumulamos el tiempo de ejecucion
  138. t1 = time.perf_counter() #seteamos el tiempo al empezar
  139. heapSort(heaplista) #ejecutamos el algoritmo heapSort
  140. acumulaHeap+=time.perf_counter()-t1 #acumulamos el tiempo de ejecucion
  141. t1 = time.perf_counter() #seteamos el tiempo al empezar
  142. quickSort(quicklista) #ejecutamos el algoritmo quickSort
  143. acumulaQuick+=time.perf_counter()-t1 #acumulamos el tiempo de ejecucion
  144. t1 = time.perf_counter() #seteamos el tiempo al empezar
  145. shellSort(searchlista) #ejecutamos el algoritmo shellSort
  146. acumulaShell+=time.perf_counter()-t1 #acumulamos el tiempo de ejecucion
  147. #imprimos los resultados
  148. print (f"Promedio de tiempo de ejecucion de {veces} listas de largo {largoLista}")
  149. print (f"MergeSort {str(acumulaMerge/veces)} segundos")
  150. print (f"HeapSort {str(acumulaHeap/veces)} segundos")
  151. print (f"QuickSort {str(acumulaQuick/veces)} segundos")
  152. print (f"ShellSort {str(acumulaShell/veces) }segundos")
  153. if __name__ == "__main__":
  154. main()