暫無描述

sorting.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #coding=utf-8
  2. """
  3. Programadores:
  4. Carlos J Corrada Bravo
  5. Diego Rodríguez
  6. Joel González
  7. Javier Santiago
  8. Luis Jusino
  9. """
  10. """
  11. Este programa calcula el promedio de tiempo de ejecución de cuatro algoritmos de ordenamiento
  12. La variable maxValor define el valor maximo de los elementos de la lista
  13. La variable largoLista define el largo de las listas a ordenar
  14. La variable veces define las veces que se va a hacer el ordenamiento
  15. Al final se imprimen los promedios de cada algortimo
  16. """
  17. from random import randint
  18. import time
  19. #===============================
  20. #Modificación a código: Diego
  21. #Añado función heapify
  22. #===============================
  23. def heapify(listaHeap, largoLista, i):
  24. largest = i
  25. left = 2 * i + 1
  26. right = 2 * i + 2
  27. if left < largoLista and listaHeap[i] < listaHeap[left]:
  28. largest = left
  29. if right < largoLista and listaHeap[largest] < listaHeap[right]:
  30. largest = right
  31. def merge(lista, p, q, r):
  32. left = lista[p:q+1] # copy the left subarray
  33. right = lista[q+1:r+1] # copy the right subarray
  34. i = 0 # index for the left subarray
  35. j = 0 # index for the right subarray
  36. k = p # index for the sorted list
  37. # Keep adding to the sorted list, while both lists have elements
  38. while i < len(left) and j < len(right):
  39. if left[i] <= right[j]:
  40. lista[k] = left[i]
  41. i += 1
  42. else:
  43. lista[k] = right[j]
  44. j += 1
  45. k += 1
  46. # If right finished first, then fill up the rest with the left subarray
  47. while i < len(left):
  48. lista[k] = left[i]
  49. i += 1
  50. k += 1
  51. # If left finished first, then fill up the rest with the right subarray
  52. while j < len(right):
  53. lista[k] = right[j]
  54. j += 1
  55. k += 1
  56. def mergeSortAux(lista, p, r):
  57. # If array has one element or less, return
  58. if p >= r:
  59. return
  60. # Else, split the array in half
  61. q = int((p+r)/2) # find the middle
  62. mergeSortAux(lista, p, q) # Sort the left subarray
  63. mergeSortAux(lista, q+1, r) # Sort the right subarray
  64. merge(lista, p, q, r) # Combine both subarrays
  65. def mergeSort(listaMerge):
  66. #definan el algoritmo de ordenamiento mergesort
  67. mergeSortAux(listaMerge, 0, len(listaMerge)-1)
  68. return listaMerge
  69. #===============================
  70. #Modificación a código: Diego
  71. #Añado función heapify
  72. #===============================
  73. def heapify(listaHeap, largoLista, i):
  74. largest = i
  75. left = 2 * i + 1
  76. right = 2 * i + 2
  77. if left < largoLista and listaHeap[i] < listaHeap[left]:
  78. largest = left
  79. if right < largoLista and listaHeap[largest] < listaHeap[right]:
  80. largest = right
  81. if largest != i:
  82. listaHeap[i], listaHeap[largest] = listaHeap[largest], listaHeap[i]
  83. heapify(listaHeap, largoLista, largest)
  84. #Fin de función heapify
  85. #===============================
  86. def heapSort(listaHeap):
  87. #definan el algoritmo de ordenamiento heapsort
  88. for i in range(len(listaHeap) / 2, -1, -1):
  89. heapify(listaHeap, len(listaHeap), i)
  90. for i in range(len(listaHeap) - 1, 0, -1):
  91. listaHeap[i], listaHeap[0] = listaHeap[0], listaHeap[i]
  92. heapify(listaHeap, i, 0)
  93. return listaHeap
  94. return lista
  95. #Se le hace referencia y se le da credito al codigo que utilice de referencia
  96. return lista
  97. #Se le da credito al programador de la funcion al final del codigo
  98. def quickSort(lista):
  99. #definan el algoritmo de ordenamiento quicksort
  100. return lista
  101. def shellSort(lista):
  102. # Subarrays are sorted according to intervals
  103. # After each set of subarrays is sorted, interval value is updated and process repeats
  104. # Function stops once iteration with interval = 1 has executed
  105. # print(lista)
  106. interval = len(lista) // 2
  107. while interval > 0:
  108. # Process repeats for each value between 1 -> interval
  109. for i in range(0, interval):
  110. # Starting index determines initial portion of the array that is sorted
  111. sortedIndex = i
  112. # Process repeats as long as the current value being considered is greater than the value to its left
  113. # Being greater than the value to its left means that it is not in the correct location
  114. j = i
  115. while j + interval < len(lista):
  116. if lista[j] > lista[j + interval]:
  117. # Swapping values so that smaller value is to the left
  118. temp = lista[j]
  119. lista[j] = lista[j + interval]
  120. lista[j + interval] = temp
  121. # print(lista)
  122. n = j
  123. # Continue comparing value that was swapped left to other values to the left to make sure it is placed in the correct location
  124. while n - interval >= 0 and lista[n] < lista[n - interval]:
  125. # Swapping values so that smaller value is to the left
  126. temp = lista[n]
  127. lista[n] = lista[n - interval]
  128. lista[n - interval] = temp
  129. n -= interval
  130. # print(lista)
  131. # Update index to continue comparison with the next value in the sub array
  132. j += interval
  133. interval //= 2
  134. # print(lista)
  135. return lista
  136. maxValor=1000 #define el valor maximo de los elementos de la lista
  137. largoLista=1000 #define el largo de las listas a ordenar
  138. veces=100 #define las veces que se va a hacer el ordenamiento
  139. acumulaMerge=0 #variable para acumular el tiempo de ejecucion del mergesort
  140. acumulaHeap=0 #variable para acumular el tiempo de ejecucion del heapsort
  141. acumulaQuick=0 #variable para acumular el tiempo de ejecucion del quicksort
  142. acumulaShell=0 #variable para acumular el tiempo de ejecucion del shellsort
  143. for i in range(veces):
  144. #Creamos una lista con valores al azar
  145. lista = [randint(0,maxValor) for r in range(largoLista)]
  146. listaMerge = lista[:]
  147. listaHeap = lista[:]
  148. listaQuick = lista[:]
  149. listaShell = lista[:]
  150. t1 = time.clock() #seteamos el tiempo al empezar
  151. mergeSort(listaMerge) #ejecutamos el algoritmo mergeSort
  152. acumulaMerge+=time.clock()-t1 #acumulamos el tiempo de ejecucion
  153. t1 = time.clock() #seteamos el tiempo al empezar
  154. heapSort(listaHeap) #ejecutamos el algoritmo heapSort
  155. acumulaHeap+=time.clock()-t1 #acumulamos el tiempo de ejecucion
  156. t1 = time.clock() #seteamos el tiempo al empezar
  157. quickSort(listaQuick) #ejecutamos el algoritmo quickSort
  158. acumulaQuick+=time.clock()-t1 #acumulamos el tiempo de ejecucion
  159. t1 = time.clock() #seteamos el tiempo al empezar
  160. shellSort(listaShell) #ejecutamos el algoritmo shellSort
  161. acumulaShell+=time.clock()-t1 #acumulamos el tiempo de ejecucion
  162. t1 = time.clock() #seteamos el tiempo al empezar
  163. quickSort(lista) #ejecutamos el algoritmo quickSort
  164. acumulaQuick+=time.clock()-t1 #acumulamos el tiempo de ejecucion
  165. t1 = time.clock() #seteamos el tiempo al empezar
  166. shellSort(lista) #ejecutamos el algoritmo shellSort
  167. acumulaShell+=time.clock()-t1 #acumulamos el tiempo de ejecucion"""
  168. #imprimos los resultados
  169. print "Promedio de tiempo de ejecucion de "+ str(veces) +" listas de largo " + str(largoLista)
  170. print "MergeSort " + str(acumulaMerge/veces) + " segundos"
  171. print "HeapSort " + str(acumulaHeap/veces) + " segundos"
  172. print "QuickSort " + str(acumulaQuick/veces) + " segundos"
  173. print "ShellSort " + str(acumulaShell/veces) + " segundos"
  174. #Referencia:
  175. #https://stackoverflow.com/questions/18262306/quicksort-with-python