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 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 select_sort(): global array if var.get() == "Selection Sort": selection_sort(array, draw_array) elif var.get() == "Insertion Sort": insertion_sort(array, draw_array) elif var.get() == "Quicksort": quick_sort(array, 0, len(array) - 1, draw_array)
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 initialize(params): if params["type"] == "quick": quick_sort("<=", params["n"], params["array"], 0, params["n"]-1) elif params["type"] == "dual": dual_pivot_qs("<=", params["n"], params["array"], 0, params["n"]-1) elif params["type"] == "qssel": qs_select(params["n"], params["array"], 0, params["n"]-1) elif params["type"] == "dpsel": dp_select(params["n"], params["array"], 0, params["n"]-1)
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_quick_sort_sorts_big_list(): """Test that quick sort sorts big list.""" from quick import quick_sort from random import shuffle big_list = list(range(100)) shuffle(big_list) assert quick_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 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 test_quick_sort(self): """ Tests the quick_sort(list) method """ data = [3, 1, 10, 9] results = quick_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [1, 3, 9, 10]) data = random.sample(range(0, 100), 10) results = quick_sort(data) self.assertEqual(results, sorted(data)) # test empty list data = [] results = quick_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, []) # test single index list data = [1] results = quick_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [1]) # test two index list data = [1, -1] results = quick_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [-1, 1]) # test three index list data = [1, -1, -5] results = quick_sort(data) self.assertIsInstance(results, list) self.assertEqual(results, [-5, -1, 1])
def test_quick_sort_with_medium_lists(unsorted_l, sorted_l): """Test quick sort with medium lists.""" from quick import quick_sort assert quick_sort(unsorted_l) == sorted_l
def test_quick_sort_sorts_small_list(): """Test that quick sort sorts small list.""" from quick import quick_sort assert quick_sort([4, 10, 7, 1, 9]) == [1, 4, 7, 9, 10]
def quick(*args): return quick_sort(*args)
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_quick_sort_on_empty_list(): """Test quick sort returns empty list on empty list.""" from quick import quick_sort assert quick_sort([]) == []
def test_quick_sort_sorts_random_list(): """Quick sort returns an ordered list.""" from quick import quick_sort input = [randint(0, 1000) for i in range(100)] expected = sorted(input) assert quick_sort(input) == expected
def test_quick_sort_returns_ordered_list(input, expected): """Quick sort returns an ordered list.""" from quick import quick_sort assert quick_sort(input) == expected
def test_quick_non_int_raises_error(): """Entering an iterable containing non-integers raises an error.""" from quick import quick_sort with pytest.raises(ValueError): quick_sort([1, 2, 3, 5, 'burp'])
def test_quick_sort_on_list_of_letters(): """Test quick sort with list of letters.""" from quick import quick_sort assert quick_sort(['b', 'f', 'p', 's', 'a']) == ['a', 'b', 'f', 'p', 's']
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 test_quick(): A = [i for i in range(100, 0, -1)] quick_sort(A, 0, len(A) - 1) assert A == B
def test_quick_sort_raises_type_error_if_input_not_list(): """Test that quick sort will raise an error if input not a list.""" with pytest.raises(TypeError): from quick import quick_sort quick_sort((1, 2, 4, 3))
def test_quick_sort_n_2_list(): """Test quick sort works on descending value list.""" from quick import quick_sort assert quick_sort([6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6]
def test_random_lists_always_sorted(to_sort, pre_sorted): """Test insertion sort works for 100 random lists.""" assert quick_sort(to_sort) == pre_sorted
def test_quick_sort_on_one_item_list(): """Test quick sort with single item list.""" from quick import quick_sort assert quick_sort([5]) == [5]
#bubble-quick for cicle in range(5): for size in range(Steps): realSize = MaxSize/Steps*size if MaxSize/Steps*size > 1 else 2 size_array.append(realSize) sequence = getSequence(realSize) bubbleSequence = sequence[:] startTime = time.time() bubble.bubble_sort(bubbleSequence) endTime = time.time() table_bubble[size][cicle] = endTime - startTime quickSequence = sequence[:] startTime = time.time() quick.quick_sort(quickSequence) endTime = time.time() table_quick[size][cicle] = endTime - startTime print size print "done-quick/bubble" #counting - k=3 for cicle in range(5): for size in range(Steps): realSize = MaxSize/Steps*size if MaxSize/Steps*size > 1 else 2 sequence = getSequence(realSize) countingSequence = sequence[:] startTime = time.time() counting.counting_sort(countingSequence,0,100)
def main(): args = sys.argv result = -1 my_time = 0 if len(args) < 3: print("Not enough input arguments! Required: [len] [v]") elif len(args) > 3: print("Too many arguments!") else: if args[1] == "--stat": try: v = int(args[2]) except ValueError: print("Arguments must be integers!") return for i in range(1000, 100001, 1000): for j in range(5): binary.compares = 0 my_list = random_list(i) quick.quick_sort(my_list, 0, len(my_list) - 1) t1_start = time.process_time() result = binary.search(my_list, v) t1_stop = time.process_time() my_time = round(t1_stop - t1_start, 8) print(result) if result == 0: print("{} is not an element of array".format(v)) else: print("{} is an element of array".format(v)) info = str(i) + ';' info += str(binary.compares) + ';' info += str(my_time) + ';' info += str(result) + ';' info += ('\n') with open("binary_stats.txt", 'a+') as f: f.write(info) else: try: n = int(args[1]) v = int(args[2]) except ValueError: print("Arguments must be integers!") return print("Elements of list: ") my_list = input().split() my_list = [int(my_list[i]) for i in range(len(my_list))] if len(my_list) != n: print("Incorrect length! ") else: if n > 0: print("Array: ", my_list) t1_start = time.process_time() result = binary.search(my_list, v) t1_stop = time.process_time() my_time = round(t1_stop - t1_start, 8) print(result) if result == 0: print("{} is not an element of array".format(v)) else: print("{} is an element of array".format(v)) print("Time: ", my_time) print("Compares: ", binary.compares) else: print("Invalid size of the array!")
def test_quick_non_list_raises_error(): """Entering a non-list/tuple param raises an error.""" from quick import quick_sort with pytest.raises(TypeError): quick_sort('Hello')