No Description

sorting.py 3.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. from copy import deepcopy
  12. import sys
  13. # This function was created to prevent program from stopping before recursion finished
  14. # Changes python's recursion limit
  15. class recursion_depth:
  16. def __init__(self, limit):
  17. self.limit = limit
  18. self.default_limit = sys.getrecursionlimit()
  19. def __enter__(self):
  20. sys.setrecursionlimit(self.limit)
  21. def __exit__(self, type, value, traceback):
  22. sys.setrecursionlimit(self.default_limit)
  23. # Mergesort algorithm
  24. def mergeSort(lista): # Ángel G. Romero Rosario on 10082022
  25. def merge(l1, l2):
  26. if len(l1) == 0:
  27. return l2
  28. elif len(l2) == 0:
  29. return l1
  30. elif l1[0] < l2[0]:
  31. return l1[0:1] + merge(l1[1:],l2) # If l1[0] < l2[0] save l1[0] first to the list and call the function again
  32. else:
  33. return l2[0:1] + merge(l1, l2[1:]) # If l2[0] < l1[0] save l2[0] first to the list and call the function again
  34. if len(lista) <= 1: # If there are no more items, return lista
  35. return lista
  36. else:
  37. mid = len(lista) // 2 # Find the middle in lista and call function to merge lista
  38. return merge(mergeSort(lista[:mid]), mergeSort(lista[mid:]))
  39. def heapSort(lista):
  40. #definan el algoritmo de ordenamiento heapsort
  41. return lista
  42. def quickSort(lista):
  43. #definan el algoritmo de ordenamiento quicksort
  44. return lista
  45. def shellSort(lista):
  46. #definan el algoritmo de ordenamiento shellsort
  47. return lista
  48. # timeCode function/thunk -> (duration, return value)
  49. # measures the time it takes for a function/thunk to return
  50. def timeCode(fn):
  51. t1 = time.perf_counter()
  52. res = fn()
  53. duration = time.perf_counter() - t1
  54. return (duration, res)
  55. maxValor = 1000 #define el valor maximo de los elementos de la lista
  56. largoLista = 1000 #define el largo de las listas a ordenar
  57. veces = 100 #define las veces que se va a hacer el ordenamiento
  58. acumulaMerge = 0 #variable para acumular el tiempo de ejecucion del mergesort
  59. acumulaHeap = 0 #variable para acumular el tiempo de ejecucion del heapsort
  60. acumulaQuick = 0 #variable para acumular el tiempo de ejecucion del quicksort
  61. acumulaShell = 0 #variable para acumular el tiempo de ejecucion del shellsort
  62. for i in range(veces):
  63. mergelista = [randint(0,maxValor) for r in range(largoLista)] #creamos una lista con valores al azar
  64. heaplista = deepcopy(mergelista)
  65. quicklista = deepcopy(mergelista)
  66. searchlista = deepcopy(mergelista)
  67. with recursion_depth(1500): # This function excedes python's recursion limit
  68. acumulaMerge += timeCode(lambda: mergeSort(mergelista))[0]
  69. acumulaHeap += timeCode(lambda: heapSort(heaplista))[0]
  70. acumulaQuick += timeCode(lambda: quickSort(quicklista))[0]
  71. acumulaShell += timeCode(lambda: shellSort(searchlista))[0]
  72. #imprimos los resultados
  73. print(f"Promedio de tiempo de ejecucion de {str(veces)} listas de largo {str(largoLista)}")
  74. print(f"MergeSort {str(acumulaMerge / veces)} segundos")
  75. print(f"HeapSort {str(acumulaHeap / veces)} segundos")
  76. print(f"QuickSort {str(acumulaQuick / veces)} segundos")
  77. print(f"ShellSort {str(acumulaShell / veces)} segundos")