Advertisement
makispaiktis

Sorting Algorithms

Jul 22nd, 2024
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.57 KB | None | 0 0
  1. from copy import deepcopy
  2.  
  3. # 1. Selection Sort
  4. def selection_sort(vector):
  5.     vec = deepcopy(vector)
  6.     LEN  = len(vec)
  7.     for i in range(LEN):
  8.         min = i
  9.         for j in range(i+1, LEN):
  10.             if vec[j] < vec[min]:
  11.                 min = j
  12.         vec[i], vec[min] = vec[min], vec[i]
  13.     return vec
  14.  
  15.  
  16.  
  17. # 2. Bubble Sort
  18. def bubble_sort(vector):
  19.     vec = deepcopy(vector)
  20.     LEN = len(vec)
  21.     for i in range(LEN):
  22.         for j in range(LEN-i-1):
  23.             if vec[j] > vec[j+1]:
  24.                 vec[j], vec[j+1] = vec[j+1], vec[j]
  25.     return vec
  26.  
  27.  
  28.  
  29. # 3. Insertion Sort
  30. def insertion_sort(vector):
  31.     vec = deepcopy(vector)
  32.     LEN = len(vec)
  33.     for i in range(1, LEN):
  34.         key = vec[i]
  35.         j = i-1
  36.         while j >= 0 and key < vec[j]:
  37.             vec[j+1], vec[j] = vec[j], vec[j+1]
  38.             j -= 1
  39.     return vec
  40.  
  41.  
  42.  
  43. # 4. Quick Sort
  44. def quick_sort(vector):
  45.     vec = deepcopy(vector)
  46.     LEN = len(vec)
  47.     if LEN <= 1:
  48.         return vec
  49.  
  50.     pivot = vec[LEN//2]
  51.     left = [x for x in vec if x < pivot]
  52.     middle = [x for x in vec if x == pivot]
  53.     right = [x for x in vec if x > pivot]
  54.     return quick_sort(left) + middle + quick_sort(right)
  55.  
  56.  
  57.  
  58. # AUXILIARY FUNCTIONS
  59. # Count Time Function
  60. def count_time(func, vector):
  61.     start = time()
  62.     sorted_vector = func(vector)
  63.     end = time()
  64.     return end - start
  65.  
  66.  
  67. # MAIN FUNCTION - EXAMPLE WITH 25 ELEMENTS
  68. from time import time
  69. from random import randrange
  70.  
  71. array = [randrange(1000) for i in range(25)]
  72.  
  73. start1 = time()
  74. array1 = selection_sort(array)
  75. end1 = time()
  76. time1 = end1 - start1
  77.  
  78. start2 = time()
  79. array2 = bubble_sort(array)
  80. end2 = time()
  81. time2 = end2 - start2
  82.  
  83. start3 = time()
  84. array3 = insertion_sort(array)
  85. end3 = time()
  86. time3 = end3 - start3
  87.  
  88. start4 = time()
  89. array4 = quick_sort(array)
  90. end4 = time()
  91. time4 = end4 - start4
  92.  
  93. print(f"Original Array: {array}\n\n")
  94. print(f"Selection Sort: {array1} ({1000*time1} ms)")
  95. print(f"Bubble Sort:    {array2} ({1000*time2} ms)")
  96. print(f"Insertion Sort: {array3} ({1000*time3} ms)")
  97. print(f"Quick Sort:     {array4} ({1000*time4} ms)")
  98.  
  99.  
  100.  
  101.  
  102. # MAIN FUNCTION - EXAMPLE WITH 1000 ELEMENTS
  103. from random import randrange
  104. from time import time
  105. from matplotlib import pyplot as plt
  106. from copy import deepcopy
  107.  
  108. # Comparison of algorithms and number of elements
  109. def run(num_elements, display_on=False):
  110.  
  111.     # Initialization
  112.     vector = [randrange(10 * num_elements) for i in range(num_elements)]
  113.     funcs = [selection_sort, bubble_sort, insertion_sort, quick_sort]
  114.     times_elapsed = []
  115.  
  116.     # Compare the sorting algorithms
  117.     print(100 * "-")
  118.     print(f"Sorting a {len(vector)}-elements vector with:\n")
  119.     for func in funcs:
  120.         time_elapsed = count_time(func, vector)
  121.         times_elapsed.append(time_elapsed)
  122.         time_shown = f"{time_elapsed:.2f} seconds" if time_elapsed >= 0.1 else f"{1000*time_elapsed:.2f} ms"
  123.         print(f"{func.__name__} ----> {time_shown}")
  124.  
  125.     # There is a choice to turn on the displays
  126.     if display_on:
  127.         print("\n")
  128.         funcs_names = [func.__name__ for func in funcs]
  129.         plt.bar(funcs_names, times_elapsed)
  130.         plt.title(f"{num_elements} ELEMENTS")
  131.         plt.ylabel("Time [seconds]")
  132.         plt.show()
  133.     print(100 * "-")
  134.     print("\n\n")
  135.     return times_elapsed
  136.  
  137.  
  138.  
  139. # Examples for various numbers of elements
  140. # Initialization
  141. num_elements_list = [100, 200, 500, 1000, 2000, 5000, 10000]
  142. flags_list = len(num_elements_list) * [False]
  143. flags_list[3] = True
  144. funcs = [selection_sort, bubble_sort, insertion_sort, quick_sort]
  145. funcs_names = [func.__name__ for func in funcs]
  146. TIMES_MATRIX = [[0 for __ in range(len(funcs))] for _ in range(len(num_elements_list))]
  147.  
  148. for i in range(len(num_elements_list)):
  149.     num_elements = num_elements_list[i]
  150.     display_on = flags_list[i]
  151.     times_elapsed = run(num_elements, display_on)
  152.     TIMES_MATRIX[i] = times_elapsed
  153. print(TIMES_MATRIX)
  154.  
  155. # Comparison of algorithms
  156. import seaborn as sns
  157. sns.set_style("darkgrid")
  158.  
  159. for j in range(len(funcs)):
  160.     trend = list()
  161.     for i in range(len(num_elements_list)):
  162.         trend.append(TIMES_MATRIX[i][j])
  163.     sns.lineplot(x=num_elements_list, y=trend, label=funcs_names[j])
  164.  
  165. plt.legend()
  166. plt.title("Comparison of algorithms")
  167. plt.xlabel("Number of elements")
  168. plt.ylabel("Time [seconds]")
  169. plt.show()
  170.  
  171.  
  172. import pandas as pd
  173. df = pd.DataFrame(TIMES_MATRIX, index=num_elements_list, columns=funcs_names)
  174. print(df)
  175. [ROWS, COLS] = df.shape
  176. df2 = df.iloc[ROWS-2:ROWS]
  177. print(df2)
  178. sns.heatmap(df2, annot=True, cmap="Blues")
  179. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement