def start_algorithm(): global data, result, numbers if not data: return if (algmenu.get() == 'Selection Sort'): selection_sort(data, drawData) drawData(data, ['Green' for x in range(len(data))]) result = "Selection Sort \n" + ' '.join(map(str, data)) data = copy.deepcopy(numbers) if (algmenu.get() == 'Insertion Sort'): insertion_sort(data, drawData) drawData(data, ['Green' for x in range(len(data))]) result = "Insertion Sort \n" + ' '.join(map(str, data)) data = copy.deepcopy(numbers) if (algmenu.get() == 'Bubble Sort'): bubble_sort(data, drawData) drawData(data, ['Green' for x in range(len(data))]) result = "Bubble Sort \n" + ' '.join(map(str, data)) data = copy.deepcopy(numbers) if (algmenu.get() == 'Quick Sort'): quick_sort(data, 0, len(data)-1, drawData) drawData(data, ['Green' for x in range(len(data))]) result = "Quick Sort \n" + ' '.join(map(str, data)) data = copy.deepcopy(numbers) if (algmenu.get() == 'Merge Sort'): merge_sort(data, 0, len(data)-1, drawData) drawData(data, ['Green' for x in range(len(data))]) result = "Merge Sort \n"' '.join(map(str, data)) data = copy.deepcopy(numbers)
def merge_sort(a, L, R, draw): if (L >= R): return m = (L + R) >> 1 merge_sort(a, L, m, draw) merge_sort(a, m + 1, R, draw) merge(a, L, R, draw)
def sorting_int_semi_rand(): print("ЧАСТИЧНО УПОРЯДОЧЕННЫЕ ЦЕЛЫЕ ЧИСЛА") for number in ranges: short = np.zeros(number, np.int64) for i in range(len(short)): short[i] = i random.shuffle(short[int(len(short) / 5):int(2 * len(short) / 5)]) random.shuffle(short[int(3 * len(short) / 5):int(4 * len(short) / 5)]) # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
def sorting_str_same_rand(): print("СТРОКИ ИЗ ОДИНАКОВЫХ ЭЛЕМЕНТОВ") for number in ranges: short = list() symbol = random.choice(string.ascii_lowercase) for i in range(number): short.append(''.join(symbol)) # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() str_radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
def sorting_short_rand(): print("РАНДОМНЫЕ МАЛЕНЬКИЕ ЧИСЛА") for number in ranges: short = np.zeros(number, np.int64) for i in range(len(short)): short[i] = i % 10 random.shuffle(short) # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
def sorting_int_same_rand(): print("МАССИВ ИЗ ОДИНАКОВЫХ ЦЕЛЫХ ЧИСЕЛ") for number in ranges: short = np.zeros(number, np.int64) for i in range(len(short)): short[i] = 654 # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
def StartAlgo(): global data if not data: return if menu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawbar, visualspeed.get()) elif menu.get() == 'Merge Sort': merge_sort(data, drawbar, visualspeed.get()) elif menu.get() == 'Bubble Sort': bubble_sort(data, drawbar, visualspeed.get()) drawbar(data, ['green' for x in range(len(data))])
def StartAlgo(): global data speedforce = 0.01 * (100 - speedscale.get()) sorter = selected_algo.get() if sorter == 'bubble SORT': bubble_sort(data, drawdata, speedforce) elif sorter == 'quick SORT': quick_sort(data, 0, len(data) - 1, drawdata, speedforce) drawdata(data, ['green' for x in range(len(data))]) elif sorter == 'merge SORT': merge_sort(data, data, 0, len(data) - 1, drawdata, speedforce)
def simulation(): bubble_time = 0 selection_time = 0 insertion_time = 0 merge_time = 0 quick_time = 0 tim_time = 0 for i in range(EXPERIMENTS): # create a list with some number of values from the given range my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() bubble_sort(my_list) bubble_time += time.time() - start my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() selection_sort(my_list) selection_time += time.time() - start my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() insertion_sort(my_list) insertion_time += time.time() - start my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() merge_sort(my_list) merge_time += time.time() - start my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() quick_sort(my_list) quick_time += time.time() - start my_list = random.sample(range(MAX_VALUE), LIST_SIZE) start = time.time() my_list.sort() tim_time += time.time() - start print('Bubble sort took', bubble_time/EXPERIMENTS*1000, 'ms') print('Selection sort took', selection_time/EXPERIMENTS*1000, 'ms') print('Insertion sort took', insertion_time/EXPERIMENTS*1000, 'ms') print('Merge sort took', merge_time/EXPERIMENTS*1000, 'ms') print('Quick sort took', quick_time/EXPERIMENTS*1000, 'ms') print('Timsort took', tim_time/EXPERIMENTS*1000, 'ms')
def test_merge_sort(fixtures): for fixture in fixtures: assert merge_sort(fixture[0]) == fixture[1] assert quick_sort(fixture[0]) == fixture[1] assert insertion_sort(fixture[0]) == fixture[1] assert bubble_sort(fixture[0]) == fixture[1] assert heap_sort(fixture[0]) == fixture[1]
def test_merge_sort_sorts_big_list(): """Test that merge sort sorts big list.""" from merge import merge_sort from random import shuffle big_list = list(range(100)) shuffle(big_list) assert merge_sort(big_list) == list(range(100))
def initialize(params): if params["type"] == "merge": merge_sort(params["comp"], params["n"], params["array"]) elif params["type"] == "quick": quick_sort(params["comp"], params["n"], params["array"], 0, params["n"] - 1) elif params["type"] == "insert": insertion_sort(params["comp"], params["n"], params["array"]) elif params["type"] == "dual": dual_pivot_qs(params["comp"], params["n"], params["array"], 0, params["n"] - 1) elif params["type"] == "hybrid": hybrid_sort(params["comp"], params["n"], params["array"])
def test_merge_sort(self): """ Tests the merge_sort(list) method """ data = [3, 1, 10, 9] results = merge_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [1, 3, 9, 10]) data = random.sample(range(0, 100), 10) results = merge_sort(data) self.assertEqual(results, sorted(data)) # test empty list data = [] results = merge_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [])
def sort(): global data if not data: return print("Selected Algorithm:" + option1.get()) if algoslec.get() == 'Bubble Sort': bubble_sort(data, visualise, float(timeslec.get())) if algoslec.get() == 'Merge Sort': merge_sort(data, visualise, float(timeslec.get())) if algoslec.get() == 'Selection Sort': select_sort(data, visualise, float(timeslec.get())) if algoslec.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, visualise, float(timeslec.get())) visualise(data, ['#D5F5E3' for x in range(len(data))])
def count_inversions(matrix, n): ind = matrix.index(0) rowmat = n - (ind // n) m = matrix[:ind] + matrix[ind + 1:] inv_matrix = merge_sort(m, 0)[1] ss = inv_matrix + rowmat if n % 2: if inv_matrix % 2 == 0: return ("identity", inv_matrix, rowmat) else: return ("other-half", inv_matrix, rowmat) if ss % 2: return ("other-half", inv_matrix, rowmat) else: return ("identity", inv_matrix, rowmat)
def any_segments_intersect(S): start = time.time() global current_x endpoints = [] segment_of = {} for (p1, p2) in S: assert p1[0] != p2[0] # don't allow vertical segments e = create_endpoint(p1, p2) segment_of[e] = (p1, p2) endpoints.append(e) e = create_endpoint(p2, p1) segment_of[e] = (p2, p1) endpoints.append(e) endpoints = merge_sort(endpoints) # To do: replace with AVLTree. -Jeremy #T = BinarySearchTree(root=None, less=segment_less) T = AVLTree(root=None, less=segment_less) for p in endpoints: current_x = p[0] s = segment_of[p] if p[1] == 0: # p is a left endpoint sn = T.insert(s) above = T.successor(sn) below = T.predecessor(sn) if above and \ segments_intersect(s[0],s[1], above.key[0], above.key[1]): print time.time() - start return (True, (s[0], s[1]), (above.key[0], above.key[1])) if below and \ segments_intersect(s[0],s[1], below.key[0], below.key[1]): print time.time() - start return (True, (s[0], s[1]), (below.key[0], below.key[1])) else: # p is a right endpoint sn = T.search(s) if sn: above = T.successor(sn) below = T.predecessor(sn) if above and below and \ segments_intersect(above.key[0], above.key[1], below.key[0], below.key[1]): print time.time() - start return (True, (above.key[0], above.key[1]), (below.key[0], below.key[1])) T.delete_node(sn) print time.time() - start return (False, None, None)
def any_segments_intersect(S): start = time.time() global current_x endpoints = [] segment_of = {} for (p1,p2) in S: assert p1[0] != p2[0] # don't allow vertical segments e = create_endpoint(p1,p2) segment_of[e] = (p1,p2) endpoints.append(e) e = create_endpoint(p2,p1) segment_of[e] = (p2,p1) endpoints.append(e) endpoints = merge_sort(endpoints) # To do: replace with AVLTree. -Jeremy #T = BinarySearchTree(root=None, less=segment_less) T = AVLTree(root=None, less=segment_less) for p in endpoints: current_x = p[0] s = segment_of[p] if p[1] == 0: # p is a left endpoint sn = T.insert(s) above = T.successor(sn) below = T.predecessor(sn) if above and \ segments_intersect(s[0],s[1], above.key[0], above.key[1]): print time.time()-start return (True, (s[0],s[1]), (above.key[0], above.key[1])) if below and \ segments_intersect(s[0],s[1], below.key[0], below.key[1]): print time.time()-start return (True, (s[0],s[1]), (below.key[0], below.key[1])) else: # p is a right endpoint sn = T.search(s) if sn: above = T.successor(sn) below = T.predecessor(sn) if above and below and \ segments_intersect(above.key[0], above.key[1], below.key[0], below.key[1]): print time.time()-start return (True, (above.key[0], above.key[1]), (below.key[0], below.key[1])) T.delete_node(sn) print time.time()-start return (False, None, None)
def merge(*args): return merge_sort(*args)
def time_merge(l): start = time.time() merge.merge_sort(l) return time.time() - start
def sorting_str_semi_rand(): print("ЧАСТИЧНО УПОРЯДОЧЕННЫЕ СТРОКИ") for number in ranges: short = list() for i in range(number): short.append(''.join( random.choice(string.ascii_lowercase) for _ in range(np.random.randint(1, 10)))) short = np.asarray(short) short[0:int(len(short) / 5)] = sorted(short[0:int(len(short) / 5)]) short[int(2 * len(short) / 5):int(3 * len(short) / 5)] = sorted( short[int(2 * len(short) / 5):int(3 * len(short) / 5)]) short[int(4 * len(short) / 5):int(5 * len(short) / 5)] = sorted( short[int(4 * len(short) / 5):int(5 * len(short) / 5)]) newshort = list() for j in range(len(short)): newshort.append(short[j]) # start = perf_counter_ns() # bubble_sort(newshort.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(newshort.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(newshort.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(newshort.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(newshort.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() str_radix_sort(newshort.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(newshort.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
import merge import quick import random import time import sys sys.setrecursionlimit(99999999) arr = random.sample(range(10000000), 10000) arr_q = arr.copy() arr_s = arr.copy() start = time.time() arr.sort() print(time.time() - start) start = time.time() merge.merge_sort(arr) print(time.time() - start) start = time.time() quick.quick_sort(arr_q, 0, len(arr_q) - 1) print(time.time() - start)
def sorting_date_semi_rand(): print("ЧАСТИЧНО УПОРЯДОЧЕННЫЕ ДАТЫ") for number in ranges: short = list() for i in range(number): date = Date(YYYY=1000, MM=random.randint(1, 12), DD=random.randint(1, 28)) short.append(date) short = np.asarray(short) short[0:int(len(short) / 5)] = sorted(short[0:int(len(short) / 5)]) short[int(2 * len(short) / 5):int(3 * len(short) / 5)] = sorted( short[int(2 * len(short) / 5):int(3 * len(short) / 5)]) short[int(4 * len(short) / 5):int(5 * len(short) / 5)] = sorted( short[int(4 * len(short) / 5):int(5 * len(short) / 5)]) # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() date_radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0
#!/usr/bin/python import insertion_asc import insertion_desc import merge a = [100,30,40,50,22,8,13,4,7,9,10,15] b = [0,30,40,50,22,8,13,4,7,9,10,15] c = [30,12,15,2,68,96,42,71] print 'asc' print 'before' print a # print before sort insertion_asc.insertion_sort_asc(a) print 'after' print a # print after sort print 'desc' print 'before' print b # print before sort insertion_desc.insertion_sort_desc(b) print 'after' print b # print after sort print 'merge' print c merge.merge_sort(c,1,len(c)) print c
def test_merge_sort(array: List[int]): """Checks that returned array is the same as result of sorted()""" assert sorted(array) == merge_sort(array)
def test_merge_sort_sorts_random_list(): """Merge sort returns an ordered list.""" from merge import merge_sort input = [randint(0, 1000) for i in range(100)] expected = sorted(input) assert merge_sort(input) == expected
def __init__(self, name, listing): # Initilization steps self.name = name listing_copy = listing listing_copy2 = listing self.listing = listing_copy ################################################## # For each algorithm, the accuracy, time, and list # will be tracked using the methods shown below ################################################## # Python sort will be used as the master sort listing_copy_py = listing_copy start = timer() self.python_sorted_list = python_sort(listing_copy_py) end = timer() self.python_sorted_time = end - start # Bubble Sort will be tested against python sort listing_copy_bu = listing_copy start = timer() self.bubble_sorted_list = bubble_sort(listing_copy_bu) end = timer() self.bubble_sort_accurate = False if self.bubble_sorted_list == self.python_sorted_list: self.bubble_sort_accurate = True self.bubble_sort_time = end - start # Selection sort will be tested against python sort listing_copy_sel = listing_copy start = timer() self.selection_sorted_list = selection_sort(listing_copy_sel) end = timer() self.selection_sort_accurate = False if self.selection_sorted_list == self.python_sorted_list: self.selection_sort_accurate = True self.selection_sort_time = end - start # Merge sort will be tested against python sort listing_copy_mer = listing_copy start = timer() self.merge_sorted_list = merge_sort(listing_copy_mer) end = timer() self.merge_sort_accurate = False if self.merge_sorted_list == self.python_sorted_list: self.merge_sort_accurate == True self.merge_sort_time = end - start #Shell root sort will be tested against python sort listing_copy_she = listing_copy start = timer() self.shell_sorted_list = shell_sort(listing_copy_she) end = timer() self.shell_accurate = False if self.shell_sorted_list == self.python_sorted_list: self.shell_accurate = True self.shell_time = end - start #Insertion sort will be tested against python sort listing_copy_ins = listing_copy start = timer() self.insertion_sorted_list = insertion_sort(listing_copy_ins) end = timer() self.insertion_accurate = False if self.insertion_sorted_list == self.python_sorted_list: self.insertion_accurate = True self.insertion_time = end - start # Heap sort will be tested against python sort listing_copy_hea = listing_copy start = timer() self.heap_sorted_list = heap_sort(listing_copy_hea) end = timer() self.heap_accurate = False if self.heap_sorted_list == self.python_sorted_list: self.heap_accurate = True self.heap_time = end - start #Strand sort will be tested against python sort listing_copy_strand = listing_copy2 start = timer() self.strand_sorted_list = strand_sort(listing_copy_strand) end = timer() self.strand_accurate = False if self.strand_sorted_list == self.python_sorted_list: self.strand_root_accurate = True self.strand_time = end - start
def test_merge_sort_returns_ordered_list(input, expected): """Merge sort returns an ordered list.""" from merge import merge_sort assert merge_sort(input) == expected
def test_merge_non_int_raises_error(): """Entering an iterable containing non-integers raises an error.""" from merge import merge_sort with pytest.raises(ValueError): merge_sort([1, 2, 3, 5, 'burp'])
def test_merge_non_list_raises_error(): """Entering a non-list/tuple param raises an error.""" from merge import merge_sort with pytest.raises(TypeError): merge_sort('Hello')
list3 = [3, 1, 5, 2, 2, 4] return list1, list2, list3 if __name__ == '__main__': # 快速排序 list1, list2, list3 = get_list() partition_sorted_list1 = partition_sort(list1) partition_sorted_list2 = partition_sort(list2) partition_sorted_list3 = partition_sort(list3) print("partition_sorted_list1: " + str(partition_sorted_list1)) print("partition_sorted_list2: " + str(partition_sorted_list2)) print("partition_sorted_list3: " + str(partition_sorted_list3)) # 归并排序 list1, list2, list3 = get_list() merge_sorted_list1 = merge_sort(list1) merge_sorted_list2 = merge_sort(list2) merge_sorted_list3 = merge_sort(list3) print("merge_sorted_list1: " + str(merge_sorted_list1)) print("merge_sorted_list2: " + str(merge_sorted_list2)) print("merge_sorted_list3: " + str(merge_sorted_list3)) # 冒泡排序 list1, list2, list3 = get_list() bubble_sorted_list1 = bubble_sort(list1) bubble_sorted_list2 = bubble_sort(list2) bubble_sorted_list3 = bubble_sort(list3) print("bubble_sorted_list1: " + str(bubble_sorted_list1)) print("bubble_sorted_list2: " + str(bubble_sorted_list2)) print("bubble_sorted_list3: " + str(bubble_sorted_list3))
M = (L + R) >> 1 i = L j = M + 1 k = L temp = [0 for _ in range(100)] while i <= M and j <= R: if a[i] < a[j]: temp[k] = a[i] k += 1 i += 1 else: temp[k] = a[j] k += 1 j += 1 while i <= M: temp[k] = a[i] k += 1 i += 1 while j <= R: temp[k] = a[j] k += 1 j += 1 for i in range(L, R + 1): a[i] = temp[i] canvas.delete("all") draw(a, L, R) time.sleep(0.1) merge_sort(heightList, 0, len(heightList) - 1, draw)
def test_sort(self): for j in range(25): array = [] for i in range(1000): array.append(randint(-100, 100)) self.assertListEqual(merge_sort(array), sorted(array))
def excec_program(list, args, file): list_dup = list.copy() swaps = 0 compares = 0 my_time = 0 if args[0] == "insert": if file: t1_start = time.process_time() insertion.insertion_sort_stat(list, args[1]) t1_stop = time.process_time() else: t1_start = time.process_time() insertion.insertion_sort(list, args[1]) t1_stop = time.process_time() swaps = insertion.swaps compares = insertion.compares my_time = round(t1_stop - t1_start, 8) elif args[0] == "merge": merge.reset_counters() if file: t1_start = time.process_time() merge.merge_sort_stat(list, args[1]) t1_stop = time.process_time() else: t1_start = time.process_time() merge.merge_sort(list, args[1]) t1_stop = time.process_time() swaps = merge.swaps compares = merge.compares my_time = round(t1_stop - t1_start, 8) elif args[0] == "quick": quick.reset_counters() if file: t1_start = time.process_time() quick.quick_sort_stat(list, 0, len(list) - 1, args[1]) t1_stop = time.process_time() else: t1_start = time.process_time() quick.quick_sort(list, 0, len(list) - 1, args[1]) t1_stop = time.process_time() swaps = quick.swaps compares = quick.compares my_time = round(t1_stop - t1_start, 8) elif args[0] == "dual_pivot": dual_pivot.reset_counters() if file: t1_start = time.process_time() dual_pivot.dual_sort_stat(list, 0, len(list) - 1, args[1]) t1_stop = time.process_time() # print(list) else: t1_start = time.process_time() dual_pivot.dual_sort(list, 0, len(list) - 1, args[1]) t1_stop = time.process_time() swaps = dual_pivot.swaps compares = dual_pivot.compares my_time = round(t1_stop - t1_start, 8) elif args[0] == "hybrid": hybrid.reset_counters() if file: t1_start = time.process_time() hybrid.hybrid_sort(list, args[1]) t1_stop = time.process_time() else: t1_start = time.process_time() hybrid.hybrid_sort(list, args[1]) t1_stop = time.process_time() swaps = hybrid.swaps compares = hybrid.compares my_time = round(t1_stop - t1_start, 8) if file: info = str(len(list)) + ';' info += str(swaps) + ';' info += str(compares) + ';' info += str(my_time) + ';' info += ('\n') try: file_name = args[2] with open(file_name,'a+') as f: f.write(info) except FileNotFoundError: print("Creating new file ...") with open(file_name,'a+') as f: f.write(info) else: print("-----------------") print("Time: %.10f" % (t1_stop - t1_start)) print("Swaps: ", swaps) print("Compares: ", compares) sorted_info(list_dup, list) if check_order: print(list) else: print("Something went wrong :( )")
def test_merge(): A = [i for i in range(100, 0, -1)] A = merge_sort(A) assert A == B
def sorting_date_same_rand(): print("МАССИВ ИЗ ОДИНАКОВЫХ ДАТ") for number in ranges: date = Date(YYYY=1000, MM=random.randint(1, 12), DD=random.randint(1, 28)) short = list() for i in range(number): short.append(date) short = np.asarray(short) # start = perf_counter_ns() # bubble_sort(short.copy()) # end = perf_counter_ns() # bubble_time = end - start # print("Сортировка пузырьком с размером массива: ", number, " Время: ", bubble_time) start = perf_counter_ns() shell_sort(short.copy()) end = perf_counter_ns() shell_time = end - start print("Сортировка Шелла с размером массива: ", number, " Время: ", shell_time) start = perf_counter_ns() quick_sort(short.copy()) end = perf_counter_ns() quick_time = end - start print("Быстрая сортировка с размером массива: ", number, " Время: ", quick_time) start = perf_counter_ns() merge_sort(short.copy()) end = perf_counter_ns() merge_time = end - start print("Сортировка слиянием с размером массива: ", number, " Время: ", merge_time) start = perf_counter_ns() heap_sort(short.copy()) end = perf_counter_ns() heap_time = end - start print("Сортировка кучей с размером массива: ", number, " Время: ", heap_time) start = perf_counter_ns() date_radix_sort(short.copy()) end = perf_counter_ns() radix_time = end - start print("Поразрядная сортировка с размером массива: ", number, " Время: ", radix_time) start = perf_counter_ns() sorted(short.copy()) end = perf_counter_ns() sorted_time = end - start print("Встроенная в язык сортировка с размером массива: ", number, " Время: ", sorted_time) return 0