def quicksort_vs_mergesort(): data = [] for i in range(4000000): random_num = random.randint(0, 4000000) data.append(random_num) start = time.time() quick_sort(data, 0, len(data) - 1) end = time.time() print( "[QUICKSORT] 4000000 (4 million) integers random numbers \n [start] " + str(end - start)) print("\n") data = [] for i in range(4000000): random_num = random.randint(0, 4000000) data.append(random_num) start = time.time() merge_sort(data) end = time.time() print( "[MERGESORT] 4000000 (4 million) integers random numbers \n [start] " + str(end - start)) print("\n")
def StartAlgorithm(): global data speed = int(speedScale.get()) if speed == 2: speed = 0.5 elif speed == 3: speed = 0.1 elif speed == 4: speed = 0.05 elif speed == 5: speed = 0.01 elif speed == 6: speed = 0.005 elif speed == 7: speed = 0.001 if selected_algo.get() == "Bubble Sort": bubble_sort(data, drawData, speed) elif selected_algo.get() == "Selection Sort": selection_sort(data, drawData, speed) elif selected_algo.get() == "Insertion Sort": insertion_sort(data, drawData, speed) elif selected_algo.get() == "Merge Sort": merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['light green' for x in range(len(data))]) time.sleep(speed) elif selected_algo.get() == "Quick Sort": quick_sort(data, drawData, speed)
def run_single_test(algorithm, list_type, list_size): sort_list = get_list(list_type, list_size) pr = cProfile.Profile() pr.enable() if algorithm == "merge_sort": mergesort.merge_sort(sort_list, 0, len(sort_list) - 1) elif algorithm == "quicksort": quicksort.quick_sort(sort_list, 0, len(sort_list) - 1) elif algorithm == "revised_quicksort": revised_quicksort.revised_quick_sort(sort_list, 0, len(sort_list) - 1, 50) elif algorithm == "shell_sort": shellsort.shell_sort(sort_list, get_shellsort_gaps(list_size)) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats("cumulative") ps.strip_dirs().print_stats() results = s.getvalue() for line in results.splitlines(): if "_sort)" in line: print(line) split_line = line.split() return (split_line[4])
def StartAlgorithm(): global data speed = int(speedScale.get()) if speed == 2: speed = 1.5 elif speed == 3: speed = 0.1 elif speed == 4: speed = 0.05 elif speed == 5: speed = 0.01 elif speed == 6: speed = 0.005 elif speed == 7: speed = 0.001 search = int(searchEntry.get()) if selected_algo.get() == "Bubble Sort": bubble_sort(data, drawData, speed) elif selected_algo.get() == "Selection Sort": selection_sort(data, drawData, speed) elif selected_algo.get() == "Insertion Sort": insertion_sort(data, drawData, speed) elif selected_algo.get() == "Merge Sort": merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['light green' for x in range(len(data))]) time.sleep(speed) elif selected_algo.get() == "Quick Sort": quick_sort(data, drawData, speed) elif algMenu.get() == 'Linear Search': linear_search(data, search, drawData, speedScale.get()) elif algMenu.get() == 'Binary Search': merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['red' for x in range(len(data))]) binary_search(data, search, drawData, speedScale.get())
def StartAlgorithm(): global data if not data: return elif algMenu.get() == 'Merge Sort': merge_sort(data, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))])
def calc_duration_merge_sort(): p = 0 r = len(A) - 1 t1 = duration.start_time() mergesort.merge_sort(A, p, r) t2 = duration.stop_time() # print("By merge sort, sorted array is: ", end="\n") # print(A) print("Merge sorting time(sec): ", duration.calc_duration(t1, t2)) print(end="\n")
def menu_de_algoritmos(): print("Analise de algoritmos separadamente") print("(1) - Quick Sort") print("(2) - Merge Sort") print("(3) - Heap Sort") print("(4) - Radix Sort") option = input("Escolha uma opção: ") quantity = [100, 1000, 10000, 100000] limit = 1000**2 if option == '1': for i in quantity: lista = cria_lista(i, limit) inicio = time.time() quick_sort(lista, 0, len(lista)) fim = time.time() result = fim - inicio print("O tempo de ordenação do quicksort em um vetor de {} elementos é de {} segundos.".format(i, result)) elif option == '2': for i in quantity: lista = cria_lista(i, limit) inicio = time.time() merge_sort(lista) fim = time.time() result = fim - inicio print("O tempo de ordenação do mergesort em um vetor de {} elementos é de {} segundos.".format(i, result)) elif option == '3': for i in quantity: lista = cria_lista(i, limit) inicio = time.time() heapsort(lista) fim = time.time() result = fim - inicio print("O tempo de ordenação do heap em um vetor de {} elementos é de {} segundos.".format(i, result)) elif option == '4': for i in quantity: lista = cria_lista(i, limit) inicio = time.time() radix_sort(lista) fim = time.time() result = fim - inicio print("O tempo de ordenação do radix em um vetor de {} elementos é de {} segundos.".format(i, result))
def StartAlgorithm(): global data if not data: return if (algMenu.get()=='Quick Sort'): quick_sort(data,0,len(data)-1,drawData,speedScale.get()) drawData(data,['green' for x in range(len(data))]) elif algMenu.get()=='Bubble Sort': bubble_sort(data, drawData, speedScale.get()) elif algMenu.get()== 'Merge Sort': merge_sort(data,drawData,speedScale.get()) drawData(data,['green' for x in range(len(data))])
def StartAlgo(): global data if not data: return if algMenu.get() == "Quick Sort": quick_sort(data, 0, len(data) - 1, draw_data, speedScale.get()) if algMenu.get() == "Bubble Sort": bubbleSort(data, draw_data, speedScale.get()) elif algMenu.get() == "Merge Sort": merge_sort(data, draw_data, speedScale.get()) draw_data(data, ["yellow" for x in range(len(data))])
def startAlgo(): global list_numbers global selected_algo global speedscale global colorArray if selected_algo.get()==av_list[0]: bubble_sort(list_numbers,draw_in_canvas,float(speedscale.get()),colorArray) elif selected_algo.get()==av_list[1]: merge_sort(list_numbers,0, len(list_numbers)-1,draw_in_canvas,float(speedscale.get())) else: quick_sort(list_numbers,0,len(list_numbers)-1,draw_in_canvas,float(speedscale.get()))
def start_algo(): print("Starting Algorithm") global data ss = speedEntry.get() ss = float(ss) # ss = 0.1 if algMenu.get() == 'quick sort': quick_sort(data, 0, len(data) - 1, drawData, ss) elif algMenu.get() == 'Bubble sort': bubble_sort(data, drawData, ss) else: merge_sort(data, drawData, ss)
def test_merge_sort(self): self.assertRaises(TypeError, merge_sort, (1, 2, 3)) self.assertRaises(TypeError, merge_sort, 1) self.assertRaises(TypeError, merge_sort, 'helloworld!') random.shuffle(self.seq) self.seq = merge_sort(self.seq) self.assertEqual(self.seq, range(self.N))
def get_median(l): n = len(l) sorted_data = merge_sort(l) if n % 2 != 0: return sorted_data[(n + 1) // 2] return get_mean(sorted_data[(n // 2):(n // 2 + 2)])
def test_merge_sort(self): self.assertEqual(merge_sort(test_case_1), test_res_1) self.assertEqual(merge_sort(test_case_2), test_res_2) self.assertEqual(merge_sort(test_case_3), test_res_3) self.assertEqual(merge_sort(test_case_4), test_res_4) self.assertEqual(merge_sort(test_case_5), test_res_5) self.assertEqual(merge_sort(test_case_6), test_res_6) self.assertEqual(merge_sort(test_case_7), test_res_7)
def test_mergesort(self): self.assertEqual(merge_sort(L1), L1_sorted) self.assertEqual(merge_sort(L2), L2_sorted) self.assertEqual(merge_sort(L3), L3_sorted) self.assertEqual(merge_sort(L4), L4_sorted) self.assertEqual(merge_sort(L5), L5_sorted) self.assertEqual(merge_sort(L6), L6_sorted) self.assertEqual(merge_sort(L7), L7_sorted)
def startAlgorithm(): global data if not data: return if algMenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawData, speedScale.get()) elif algMenu.get() == 'Bubble Sort': bubble_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Merge Sort': merge_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Selection Sort': selection_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Heap Sort': heap_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Insertion Sort': insertion_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Shell Sort': shell_sort(data, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))])
def start_algo(): global data if not data: return if algoMenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, draw_Data, speedScale.get()) elif algoMenu.get() == 'Bubble sort': bubble_sort(data, draw_Data, speedScale.get()) elif algoMenu.get() == 'Merge Sort': merge_sort(data, draw_Data, speedScale.get()) elif algoMenu.get() == 'Insertion Sort': insertion_sort(data, draw_Data, speedScale.get()) elif algoMenu.get() == 'Heap Sort': heap_sort(data, draw_Data, speedScale.get()) draw_Data(data, ['green' for x in range(len(data))])
def comparativo_de_algoritmos(): limit = 1000**2 results_quicksort = [] results_mergesort = [] results_heapsort = [] results_radixsort = [] for i in range(0,100): lista = cria_lista(1000, limit) lista_quick = lista inicio = time.time() quick_sort(lista_quick, 0, len(lista_quick)) fim = time.time() tempo = fim - inicio results_quicksort.append(tempo) lista_merge = lista inicio = time.time() merge_sort(lista_merge) fim = time.time() tempo = fim - inicio results_mergesort.append(tempo) lista_heap = lista inicio = time.time() heapsort(lista_heap) fim = time.time() tempo = fim - inicio results_heapsort.append(tempo) lista_radix = lista inicio = time.time() radix_sort(lista_radix) fim = time.time() tempo = fim - inicio results_radixsort.append(tempo) plota_grafico(results_quicksort, results_mergesort, results_heapsort, results_radixsort)
def test_multiple_elements(self): """Tests cases where we have more than 2 elements.""" # Even length lists self.assertEqual(merge_sort([-100, 100, -5, 4]), [-100, -5, 4, 100]) self.assertEqual(merge_sort([100, 4, -5, -100]), [-100, -5, 4, 100]) self.assertEqual(merge_sort([1, 2, 3, 4, 5, 6]), [1, 2, 3, 4, 5, 6]) self.assertEqual(merge_sort([6, 5, 4, 3, 2, 1]), [1, 2, 3, 4, 5, 6]) self.assertEqual(merge_sort([1, 5, 4, 6, 2, 3]), [1, 2, 3, 4, 5, 6]) test_list = [1, 5, 2, 6, 3, 7, 4, 8, 5, 9] self.assertEqual(merge_sort(test_list), [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]) # Odd length list self.assertEqual(merge_sort([0, 10, 11, 15, 25]), [0, 10, 11, 15, 25]) self.assertEqual(merge_sort([15, 10, 25, 0, 11]), [0, 10, 11, 15, 25])
def quicksort_vs_mergesort(): lista = [] for i in range(4000000): aleatorio = random.randint(0, 4000000) lista.append(aleatorio) tempo = time.time() quick_sort(lista, 0, len(lista) - 1) fim = time.time() print("[QUICKSORT] 4000000 (4 milhoes) inteiros Aleatorios\n[TEMPO] "+ str(fim - tempo)) lista = [] for i in range(4000000): aleatorio = random.randint(0, 4000000) lista.append(aleatorio) tempo = time.time() merge_sort(lista) fim = time.time() print("[MERGESORT] 4000000 (4 milhoes) inteiros Aleatorios\n[TEMPO] "+ str(fim - tempo)) print("\n")
def test_merge_sort(self): """ Test for merge_sort """ list1 = [1] list2 = [2, 1] list3 = [4,5,9,8,7] list4 = [6,4,5,2,7,1] list1_expected = [1] list2_expected = [1,2] list3_expected = [4,5,7,8,9] list4_expected = [1,2,4,5,6,7] mergesort.merge_sort(list1) mergesort.merge_sort(list2) mergesort.merge_sort(list3) mergesort.merge_sort(list4) self.assertEqual(list1, list1_expected) self.assertEqual(list2, list2_expected) self.assertEqual(list3, list3_expected) self.assertEqual(list4, list4_expected)
def test_sort_already_sorted(self): array = [1, 2] result = ms.merge_sort(array) self.assertEquals(array, result)
def test_sort_one_value(self): array = [4] result = ms.merge_sort(array) self.assertEquals(array, result)
Vertices_List = [] for items in a_List: # Listing all the vertices Vertices_List.append(items[0]) Vertices_List.append(items[1]) vertices = [] # Contains all the unique vertex for item in Vertices_List: if item not in vertices: vertices.append(item) parent_array = [] # initializing the disjoints set for i in range(len(vertices) + 1): parent_array.append(-1) sorted_edges = merge_sort( a_List) #sorted_edges contains the sorted list by weight def find(a): if parent_array[a] < 0: # find root of the tree containing ‘a’ return a parent_array[a] = find(parent_array[a]) return parent_array[a] def union(a, b): # by height root_a = find(a) # find root of tree containing ‘a’ root_b = find(b) # find root of tree containing ‘b’ if root_a == root_b: # ‘a’ and ‘b’ in the same tree return height_a = -parent_array[root_a] # height of tree containing ‘a’
def hamming_dist(): """ This function will find the hamming distance with <= 1 It splits the words into 2 parts. Then it takes the First portion of the word. Does Boyer Moore on it to find all the exact occurrences. Then it accesses the portion of the TEXT that has the exact occurrences. And then iterates through the 2nd part of the pattern. It there are more than 1 mismatch it will not take that position. This theory is known as the pigeon hole principal. After doing the first part, it will also do the same thing with the 2nd part of the pattern. :return: List with hamming distance less than or equal to 1 """ split_word = odd_or_even_length(pat) # splits word into 2 parts first_part = split_word[0] # first part second_part = split_word[1] # second part hamming_list = [] #hamming list first_part_boyer_moore = BoyerMoore(text, first_part) if len(first_part_boyer_moore ) > 0: # if list is not empty only then it will check if first_part_boyer_moore[-1] + len(pat) > len(text): first_part_boyer_moore.remove(first_part_boyer_moore[-1]) for items in first_part_boyer_moore: counter = 0 for j in range(len(second_part)): if counter >= 2: break if text[items + len(first_part) + j] != pat[len(first_part) + j]: counter += 1 if counter <= 1: hamming_list.append([items, counter]) second_part_boyer_moore = BoyerMoore(text, second_part) # 2nd part if len(second_part_boyer_moore) > 0: if second_part_boyer_moore[0] - len(first_part) < 0: second_part_boyer_moore.remove(second_part_boyer_moore[0]) for items in second_part_boyer_moore: counter = 0 for j in range(len(first_part) - 1, -1, -1): if counter >= 2: break if text[items - len(first_part) + j] != pat[j]: counter += 1 if counter <= 1: hamming_list.append([items - len(first_part), counter]) if len(hamming_list) > 0: # if list is not empty filtering_duplicates = [] for items in hamming_list: if items not in filtering_duplicates: filtering_duplicates.append(items) filtering_duplicates = (merge_sort(filtering_duplicates)) f = open('output_hammingdist.txt', 'w') for a, b in filtering_duplicates: f.write('{:>0} {:>1}\n'.format(a, b)) f.close()
def test_empty_and_single_element(self): """Tests the trivial cases for empty and single element lists.""" self.assertEqual(merge_sort([]), []) self.assertEqual(merge_sort([0]), [0]) self.assertEqual(merge_sort(["Banana"]), ["Banana"])
def test_sorts_correctly(self): new_array = self.unsorted[:] new_array.sort() self.assertEqual(new_array, merge_sort(self.unsorted))
def _do_test_merge_sort(self, merge_func): A = [] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, []) A = [6] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, [6]) A = [1,2] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, [1,2]) A = [2,1] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, [1,2]) A = [1,1] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, [1,1]) A = [2,2,2,1] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, [1,2,2,2]) A = ["2","2","2","1"] mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, ["1","2","2","2"]) NITEMS = 2**20 Expected = [randint(0, NITEMS) for i in range(NITEMS)] A = Expected.copy() Expected.sort() mergesort.merge_sort(A,0,len(A),merge_func) self.assertEqual(A, Expected)
if __name__ == "__main__": import random import time from mergesort import merge_sort from bubblesort import bubble_sort # a=[3,8,2,5,1,4,7,6] v = [random.random() for x in xrange(1000000)] av = v[:] start = time.time() quick_sort(av, 0, len(av)) end = time.time() print "quick time: %.3f seconds" % (end - start) bv = v[:] start = time.time() merge_sort(bv) end = time.time() print "merge time: %.3f seconds" % (end - start) """ cv=v[:] start=time.time() bubble_sort(cv) end=time.time() print "time: %.3f seconds"%(end-start) """
def __init__(self): self.arrayGenerator = arrayGenerator() self.sorter = mergesort.merge_sort()
def test_merge_sort(self): sorted_numbers = list(range(1000000)) shuffled_numbers = sorted_numbers[:] random.shuffle(shuffled_numbers) self.assertEqual(merge_sort(shuffled_numbers), sorted_numbers)
def test_already_sorted(self): self.assertEqual(self.array, merge_sort(self.array))
def test_sort_simple_2_values(self): array = [2, 1] result = ms.merge_sort(array) self.assertEquals([1, 2], result)
import time import random from bubblesort import bubble_sort from insertsort import insert_sort from mergesort import merge_sort from quicksort import quick_sort from heapsort import heap_sort items = [random.randint(-50, 100) for i in range(10)] time0 = time.time() bubble_sort(items) time1 = time.time() insert_sort(items) time2 = time.time() merge_sort(items) time3 = time.time() quick_sort(items) time4 = time.time() heap_sort(items) time5 = time.time() items.sort() time6 = time.time() print() print(" typ │ time [ms] ") print("─────────────────────┼─────────────────────") print(" Bubble sort │ {:.15f}".format(time1 - time0)) print(" Insertion sort │ {:.15f}".format(time2 - time1)) print(" Merge sort │ {:.15f}".format(time3 - time2)) print(" Quicksort │ {:.15f}".format(time4 - time3))
def test_sort_uneven(self): array = [11, 5, 3, 4, 1] result = ms.merge_sort(array) expected = [1, 3, 4, 5, 11] self.assertEquals(expected, result)
def test_merge_sort(self): self.assertEqual(merge_sort([9,8,7,6,5,4,3,2,1]), [1,2,3,4,5,6,7,8,9]) self.assertEqual(merge_sort([9,8,7,6,6,5,23,1]), [1,5,6,6,7,8,9,23])
from mergesort import merge_sort,merge from insertionsort import insertion_sort from time import time import random import matplotlib.pyplot as plt time_arr=[] size_arr=[] #for i in range(0,1100,100): #For insertion sort for i in range(10000,110000,10000): #For merge sort size_arr.append(i) random_values = random.sample(range(i),i) value_length=len(random_values) start=time() # insertion_sort(random_values) merge_sort(random_values) end=time() time_arr.append(end-start) print(end-start) #Plotting plt.plot(size_arr,time_arr) plt.title("MERGE SORT") #For Merge Sort # plt.title("INSERTION SORT") #For Insertion Sort plt.xlabel("Random Values") plt.ylabel("Time taken (in seconds)") plt.show()
def test_sorts_sorted_list(self): l = [1, 2, 3, 4] l = merge_sort(l) self.assertListEqual(l, [1, 2, 3, 4])
def test_sorts_revere_list(self): l = [5, 4, 3, 2, 1, 0, -1] l = merge_sort(l) self.assertListEqual(l, [-1, 0, 1, 2, 3, 4, 5])
def test_two_elements(self): """Tests cases where the list has only 2 elements.""" self.assertEqual(merge_sort([0, 0]), [0, 0]) self.assertEqual(merge_sort([0, 1]), [0, 1]) self.assertEqual(merge_sort([1, 0]), [0, 1]) self.assertEqual(merge_sort([100, -100]), [-100, 100])
def do_mergesort(): arr = read_array(args.input) arr = merge_sort(arr) print_array(args.output, arr)
def test_sorts_empty_list(self): l = [] l = merge_sort(l) self.assertListEqual(l, [])