Nenhuma descrição

sorting.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. La variable veces define las veces que se va a hacer el ordenamiento
  8. Al final se imprimen los promedios de cada algortimo
  9. """
  10. from random import randint
  11. import time
  12. from merge import merge
  13. import heapq
  14. # Python program for implementation of MergeSort
  15. # Merges two subarrays of arr[].
  16. # First subarray is arr[l..m]
  17. # Second subarray is arr[m+1..r]
  18. def mergeSort(lista, l, r):
  19. if l < r:
  20. # Same as (l+r)//2, but avoids overflow for
  21. # large l and h
  22. m = l+(r-l)//2
  23. # Sort first and second halves
  24. mergeSort(lista, l, m)
  25. mergeSort(lista, m+1, r)
  26. merge(lista, l, m, r)
  27. ''' Luis Andrés López Mañán
  28. Program written by hand as a draft on 09/19/2022
  29. Credit goes to GeeksForGeeks
  30. Link: https://www.geeksforgeeks.org/python-program-for-heap-sort/
  31. Last access on 09/19/2022
  32. Program wrriten and edited on 10/10/2022
  33. '''
  34. # This function heapifies a subtree rooted at an index
  35. # i. Also, n is the size of a heap and arr is array.
  36. def heapify(lista, n, i):
  37. # largest is root for now
  38. largest = i
  39. # left child of root
  40. l = 2 * i + 1
  41. # right child of root
  42. r = 2 * i + 2
  43. # Checks if root has a left child and is greater than root
  44. if l < n and lista[i] < lista[l] :
  45. largest = l
  46. # Checks if root has a right child and is greater than root
  47. if r < n and lista[largest] < lista[r]:
  48. largest = r
  49. # If necessary, this changes root by swapping values
  50. if largest != i:
  51. lista[i], lista[largest] = lista[largest], lista[i]
  52. # This heapifies the root repeatedly
  53. heapify(lista, n, largest)
  54. def heapSort(lista):
  55. n = len(lista)
  56. n2 = (n // 2) - 1
  57. nMinus = n - 1
  58. for i in range(n2, -1, -1):
  59. heapify(lista, n, i)
  60. for i in range(nMinus, -1, -1):
  61. lista[i], lista[0] = lista[0], lista[i]
  62. heapify(lista, i, 0)
  63. return lista
  64. def quickSort(lista):
  65. #definan el algoritmo de ordenamiento quicksort
  66. elements = len(lista)
  67. #Base case
  68. if elements < 2:
  69. return lista
  70. current_position = 0 #Position of the partitioning element
  71. for i in range(1, elements): #Partitioning loop
  72. if lista[i] <= lista[0]:
  73. current_position += 1
  74. temp = lista[i]
  75. lista[i] = lista[current_position]
  76. lista[current_position] = temp
  77. temp = lista[0]
  78. lista[0] = lista[current_position]
  79. lista[current_position] = temp #Brings pivot to it's appropriate position
  80. left = quickSort(lista[0:current_position]) #Sorts the elements to the left of pivot
  81. right = quickSort(lista[current_position+1:elements]) #sorts the elements to the right of pivot
  82. lista = left + [lista[current_position]] + right #Merging everything together
  83. return lista
  84. '''
  85. This algorithm was taken from: https://www.programiz.com/dsa/shell-sort
  86. and was adapted in order to work for this assigment.
  87. '''
  88. def shellSort(lista):
  89. #definan el algoritmo de ordenamiento shellsort
  90. # determening the size of the list and calculates the gap value.
  91. n = len(lista)
  92. gap = n // 2
  93. # this algorithm will run until gap reaches 1
  94. while gap > 0:
  95. for i in range(gap, n):
  96. temp = lista[i] # storing all items from the list into temp
  97. j = i
  98. # compares the number in temp with the 0th possition (start of list)
  99. # if temp is larger than the first element then we swap them
  100. while j >= gap and lista[j - gap] > temp:
  101. lista[j] = lista[j - gap]
  102. j -= gap
  103. lista[j] = temp
  104. gap = gap // 2 # decreases the gap to continue the loop
  105. return lista
  106. maxValor=1000 #define el valor maximo de los elementos de la lista
  107. largoLista=1000 #define el largo de las listas a ordenar
  108. veces=100 #define las veces que se va a hacer el ordenamiento
  109. acumulaMerge=0 #variable para acumular el tiempo de ejecucion del mergesort
  110. acumulaHeap=0 #variable para acumular el tiempo de ejecucion del heapsort
  111. acumulaQuick=0 #variable para acumular el tiempo de ejecucion del quicksort
  112. acumulaShell=0 #variable para acumular el tiempo de ejecucion del shellsort
  113. for i in range(veces):
  114. mergelista = [randint(0,maxValor) for r in range(largoLista)] #creamos una lista con valores al azar
  115. heaplista=list(mergelista)
  116. quicklista=list(mergelista)
  117. searchlista=list(mergelista)
  118. t1 = time.process_time() #tomamos el tiempo inicial
  119. mergeSort(mergelista,0,len(mergelista)-1) #ejecutamos el algoritmo mergeSort
  120. acumulaMerge+=time.process_time() - t1 #acumulamos el tiempo de ejecucion
  121. #print(mergelista) #desplegamos la lista
  122. t1 = time.process_time() #tomamos el tiempo inicial
  123. heapSort(heaplista) #ejecutamos el algoritmo heapSort
  124. acumulaHeap+=time.process_time() - t1 #acumulamos el tiempo de ejecucion
  125. #print(heaplista) #desplegamos la lista
  126. t1 = time.process_time() #tomamos el tiempo inicial
  127. quickresult = quickSort(quicklista) #ejecutamos el algoritmo quickSort
  128. acumulaQuick+=time.process_time() - t1 #acumulamos el tiempo de ejecucion
  129. print(quicklista) #desplegamos la lista
  130. t1 = time.process_time() #tomamos el tiempo inicial
  131. shellSort(searchlista) #ejecutamos el algoritmo shellSort
  132. acumulaShell+=time.process_time() - t1 #acumulamos el tiempo de ejecucion
  133. print(searchlista) #desplegamos la lista
  134. #imprimos los resultados
  135. print ("Promedio de tiempo de ejecucion de "+ str(veces) +" listas de largo " + str(largoLista))
  136. print ("MergeSort " + str(acumulaMerge/veces) + " segundos")
  137. print ("HeapSort " + str(acumulaHeap/veces) + " segundos")
  138. print ("QuickSort " + str(acumulaQuick/veces) + " segundos")
  139. print ("ShellSort " + str(acumulaShell/veces) + " segundos")