def _check_duplicate(chosen, output): if len(output) == 0: return False selection_sort(chosen) for e in output: selection_sort(e) if chosen == e: return True return False
def visualize_selection_sort(lst, vis): start_time = time.perf_counter_ns() sort.selection_sort(lst, vis) end_time = time.perf_counter_ns() vis.replay(0) vis.reset() print('Selection Sort') print(f'Time: {end_time - start_time:,}ns\n')
def test_sort(self): # Set up array to sort array_len = 1024 max_value = 1024 x = [random.randint(0, max_value) for i in range(array_len)] # Insertion sort self.assertEqual(sort.insertion_sort(x), sorted(x)) # Merge sort self.assertEqual(sort.merge_sort(x), sorted(x)) # Selection sort self.assertEqual(sort.selection_sort(x), sorted(x)) # Bubble sort self.assertEqual(sort.bubble_sort(x), sorted(x)) # Heap sort self.assertEqual(sort.heap_sort(x), sorted(x)) # Quick sort self.assertEqual(sort.quick_sort(x), sorted(x)) # Quick sort v2 self.assertEqual(sort.quick_sort_v2(x), sorted(x))
def test_selection_sort(): alist = range(10) random.shuffle(alist) ret = sort.selection_sort(alist) assert ret == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_selection_sort(): assert_equal(selection_sort([1, 2, 3]), [1, 2, 3]) assert_equal(selection_sort([3, 2, 1]), [1, 2, 3]) assert_equal(selection_sort([2, 1, 3]), [1, 2, 3]) assert_equal(selection_sort([55, -4, 34, 34, 15]), [-4, 15, 34, 34, 55]) assert_equal(selection_sort([0.4, 567, -10006, 23, 0, 5]), [-10006, 0, 0.4, 5, 23, 567]) assert_equal(selection_sort([7]), [7]) assert_equal(selection_sort([]), []) assert_equal(selection_sort(None), None)
def test_selection_sort(): print "\nselection sort begin" count = random.randint(100, 1000) for _ in range(count): length = random.randint(5, 30) source = tool.random_list(0, 100, length) target = sort.selection_sort(source) if tool.list_is_ascend(target) is False: print source print target print "" assert (tool.list_is_ascend(target)) print "selection sort success in {0} times.\n".format(count)
def graph_menu(): os.system('cls||clear') with open('disciplines.json') as f: disciplines = json.load(f) print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Estrutura de Dados 2 - Algoritmos de Ordenção O(n²)\n') print('==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Ordernar por : ' + '\n') print('[1] - Código da Matéria') print('[2] - Nome da Matéria') print('[3] - Sair') print('') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n' + '\033[0m') param = int(input('>>>')) param = 'name' if (param > 1) else 'code' runtime = [] sort = ['Insertion Sort', 'Selection Sort', 'Bubble Sort'] start = time.time() i = insertion_sort(disciplines, param) end = time.time() runtime.append(end - start) with open('disciplines.json') as f: disciplines = json.load(f) start = time.time() i = selection_sort(disciplines, param) end = time.time() runtime.append(end - start) with open('disciplines.json') as f: disciplines = json.load(f) start = time.time() i = bubble_sort(disciplines, param) end = time.time() runtime.append(end - start) print(runtime) plt.figure(figsize=(10,5)) plt.barh(sort, runtime, color='blue') plt.xlabel('Tempo de execução') plt.show()
def test_sorted_list(): data_size = 1000 seed(42) orig_data = sample(range(data_size * 3), k=data_size) assert not is_sorted(orig_data) test_data = selection_sort(orig_data.copy()) assert is_sorted(test_data) test_data = insertion_sort(orig_data.copy()) assert is_sorted(test_data) test_data = mergesort(orig_data.copy()) assert is_sorted(test_data) test_data = quicksort(orig_data.copy()) assert is_sorted(test_data)
def test_sorted_list(self): data_size = 1000 seed(42) orig_data = sample(range(data_size * 3), k=data_size) self.assertFalse(is_sorted(orig_data)) test_data = selection_sort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = insertion_sort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = mergesort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = quicksort(orig_data.copy()) self.assertTrue(is_sorted(test_data))
def test_sort_times(self): data_size = 1000 seed(42) data = sample(range(data_size * 3), k=data_size) # selection sort test = data.copy() start = perf_counter() test = selection_sort(test) selection_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # insertion sort test = data.copy() start = perf_counter() test = insertion_sort(test) insertion_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # merge sort test = data.copy() start = perf_counter() test = mergesort(test) merge_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # quick sort test = data.copy() start = perf_counter() test = quicksort(test) quick_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # tim sort test = data.copy() start = perf_counter() test.sort() tim_elapsed_time = perf_counter() - start self.assertLess(merge_elapsed_time, insertion_elapsed_time) self.assertLess(quick_elapsed_time, selection_elapsed_time) self.assertLess(tim_elapsed_time, merge_elapsed_time)
def test_sort_times(): data_size = 1000 seed(42) data = sample(range(data_size * 3), k=data_size) # selection sort test = data.copy() start = perf_counter() test = selection_sort(test) selection_elapsed_time = perf_counter() - start assert is_sorted(test) # insertion sort test = data.copy() start = perf_counter() test = insertion_sort(test) insertion_elapsed_time = perf_counter() - start assert is_sorted(test) # merge sort test = data.copy() start = perf_counter() test = mergesort(test) merge_elapsed_time = perf_counter() - start assert is_sorted(test) # quick sort test = data.copy() start = perf_counter() test = quicksort(test) quick_elapsed_time = perf_counter() - start assert is_sorted(test) # tim sort test = data.copy() start = perf_counter() test.sort() tim_elapsed_time = perf_counter() - start assert merge_elapsed_time < insertion_elapsed_time assert quick_elapsed_time < selection_elapsed_time assert tim_elapsed_time < merge_elapsed_time
def main(): global RANGE global iSIZE global ROUND global PRINT size = iSIZE #Selection Sort Test test_name = "Selection Sort - unsorted" print("*******************************") print(f"Test Name:\t{test_name}") print("*******************************") sel_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() sel_sorted_lists.append(sort.selection_sort(list)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, ROUND))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Selection Sort - sorted" for i in range(0, RANGE): t1 = time.clock() sort.selection_sort(sel_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(sel_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(sel_sorted_lists[i]), round(ticks, ROUND))]) print("\n...Performing tests with reverse sorted lists...\n") test_name = "Selection Sort - reverse sorted" for i in range(0, RANGE): sel_sorted_lists[i].reverse() t1 = time.clock() sort.selection_sort(sel_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(sel_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(sel_sorted_lists[i]), round(ticks, ROUND))]) #Merge Sort Test test_name = "Merge Sort - unsorted" print("\n*******************************") print(f"Test Name:\t{test_name}") print("*******************************") merg_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() merg_sorted_lists.append(sort.merge_sort(list)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, 4))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Merge Sort - sorted" for i in range(0, RANGE): t1 = time.clock() sort.merge_sort(merg_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(merg_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(merg_sorted_lists[i]), round(ticks, 4))]) print("\n...Performing tests with sorted reverse lists...\n") test_name = "Merge Sort - reverse sorted" for i in range(0, RANGE): merg_sorted_lists[i].reverse() t1 = time.clock() sort.merge_sort(merg_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(merg_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(merg_sorted_lists[i]), round(ticks, 4))]) #Counting Sort Test size = iSIZE test_name = "Counting Sort - unsorted" print("\n*******************************") print(f"Test Name:\t{test_name}") print("*******************************") count_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() count_sorted_lists.append(sort.count_sort(list, size)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, ROUND))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Counting Sort - sorted" for i in range(0, RANGE): max = len(count_sorted_lists[i]) t1 = time.clock() sort.count_sort(count_sorted_lists[i], max) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(count_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(count_sorted_lists[i]), round(ticks, ROUND))]) print("\n...Performing tests with reverse sorted lists...\n") test_name = "Counting Sort - reverse sorted" for i in range(0, RANGE): count_sorted_lists[i].reverse() max = len(count_sorted_lists[i]) t1 = time.clock() sort.count_sort(count_sorted_lists[i], max) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, max, ticks, ROUND) myUtils.write_to_file([(test_name, max, round(ticks, ROUND))])
def test_selection_sort(items, expected): assert selection_sort(items) == expected
def test_selection_sort(): l = [2, 1, 3, -5, 3, 4] sort.selection_sort(l) assert l == [-5, 1, 2, 3, 3, 4]
def tests_selection_sort(self): """ Test Selection Sort. read sort.py for instructions. """ sample = [3, 1, 10, 5, 654, 45, 8, 5, 31, 123] sorted_sample = [1, 3, 5, 5, 8, 10, 31, 45, 123, 654] self.assertEqual(sorted_sample, sort.selection_sort(sample))
from sort import bubble_sort from sort import selection_sort import numpy as np print('Enter the array size n') array = np.zeros(int(input())) for j in range(np.size(array)): print('Enter a[', j, ']=') array[j] = int(input()) print('array:', array) print('which algorithm you want to use…\nbubble_sort : 1\nselection_sort: 2') b = int(input()) if b == 1: print('Bubble_sort:') bubble_sort(array) if b == 2: print('Selection_sort:') selection_sort(array) if b != 1 and b != 2: print('No sort') print(array)
if __name__ == '__main__': start = time.time() data = array.array('i', range(1, LISTNUM)) mix_data(data) args = sys.argv if len(args) < 2: sys.exit("[error] select option") if args[1] == "-in": sort.insertion_sort(data) elif args[1] == "-bu": sort.bubble_sort(data) elif args[1] == "-se": sort.selection_sort(data) elif args[1] == "-me": sort.merge_sort(data) elif args[1] == "-qu": sort.quick_sort(data) elif args[1] == "-lsd": sort.lsd_radix_sort(data) elif args[1] == "-msd": sort.msd_radix_sort(data) elif args[1] == "-sh": sort.shell_sort(data) elif args[1] == "-sk": sort.shaker_sort(data) elif args[1] == "-he": sort.heap_sort(data) elif args[1] == "-cm":
import time import random #再帰条件の変更 import sys sys.setrecursionlimit(100000) l = list(range(3000)) random.shuffle(l) start_time = time.time() sorted_list = sort.bubble_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.selection_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.insertion_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.heap_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.merge_sort(l) #print(sorted_list) print('time:{0:.3f}'.format(time.time()-start_time))
sort.comb_sort(b) print b b = a[:] sort.shell_sort(b) print b b = a[:] sort.shell_sort(b, None, 'shell') print b b = a[:] sort.shell_sort(b, None, 'cuira') print b b = a[:] sort.insertion_sort(b) print b b = a[:] sort.coctail_sort(b) print b b = a[:] sort.selection_sort(b) print b b = a[:] sort.bubble_sort(b) print b
def discipline_menu(): os.system('cls||clear') with open('disciplines.json') as f: disciplines = json.load(f) print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Estrutura de Dados 2 - Algoritmos de Ordenção O(n²)\n') print('==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Selecione uma opção de busca: ' + '\n') print('[1] - Selection Sort') print('[2] - Insertion Sort') print('[3] - Bubble Sort') print('[4] - Sair') print('') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n' + '\033[0m') option = int(input('>>>')) while(option not in [1, 2, 3, 4]): option = int(input("Insira uma opção válida: ")) if(option == 4): sys.exit() os.system('cls||clear') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Estrutura de Dados 2 - Algoritmos de Ordenção O(n²)\n') print('==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Ordernar por : ' + '\n') print('[1] - Código da Matéria') print('[2] - Nome da Matéria') print('[3] - Sair') print('') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n' + '\033[0m') param = int(input('>>>')) while(option not in [1, 2, 3]): option = int(input("Insira uma opção válida: ")) if(param == 3): sys.exit() param = 'name' if (param > 1) else 'code' if(option == 1): start = time.time() disciplines = selection_sort(disciplines, param) end = time.time() runtime = end - start elif(option == 2): start = time.time() disciplines = insertion_sort(disciplines, param) end = time.time() runtime = end - start else: start = time.time() disciplines = bubble_sort(disciplines, param) end = time.time() runtime = end - start os.system('cls||clear') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') for i in range(0, 45): print(disciplines[i]['code'], '-', disciplines[i]['name']) print('\033[0m', '\n', 'Tempo de execução:', runtime) print('\n'+ '\033[1m' + '==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n' + '\033[0m')
def test_selection_sort(self): self.assertEqual(sort.selection_sort(self.before), self.after)
def test_empty_list(self): l = [] selection_sort(l) self.assertEqual(l, [])
for i in range(size): while True: try: print(1 + i) elements = int(input("Masukkan nilai : \t")) lst.append(elements) break except ValueError: print("Masukkan angka bos!") print("1. Bubble \n2. Insertion \n3. Merge \n4. Quick \n5. Selection") while True: try: arg = int(input("Pilihan: \t")) break except ValueError: print("Masukkan angka bos!") if arg == 1: sort.bubble_sort(lst) elif arg == 2: sort.insertion_sort(lst) elif arg == 3: sort.merge_sort(lst) elif arg == 4: sort.quick_sort(lst) elif arg == 5: sort.selection_sort(lst) else: print("Pilihan Tidak ada")
def cpu_bounded_func(n=CPU_FUNC_NUMBER): return selection_sort(n)
def test_sorted_list(self): l = [1, 2, 3, 4, 5] selection_sort(l) self.assertEqual(l, [1, 2, 3, 4, 5])
def main(): win = gp.GraphWin('sortpy', WINDOW_X, WINDOW_Y, autoflush=False) win.setBackground(color=gp.color_rgb(43, 137, 164)) print_logo() first_input = True while 1: clear_screen(win) ds = sort.generate_dataset(sort.DATA_NUM, repeat=False) bars = [] draw_bars(ds, win, bars) sort.playback_list = [] valid_command = False if first_input: command = input('Type help to view commands\n') first_input = False else: command = input('') while not valid_command: if command == 'help': print_header('Sorting algorithms') print_subheader('Bubble sorts') print_command('bubble', 'Bubble sort') print_command('cocktail', 'Cocktail shaker sort') print_command('comb', 'Comb sort') print_command('oddeven', 'Odd-even sort') print_subheader('Insertion sorts') print_command('insertion', 'Insertion sort') print_command('shell', 'Shellsort') print_command('gnome', 'Gnome sort') print_subheader('Divide and conquer') print_command('merge', 'Merge sort') print_command('quick', 'Quicksort') print_subheader('Other') print_command('selection', 'Selection sort') print_command('stooge', 'Stooge sort') print_header('Options') print_command('quit', 'Exit sortpy') print('\n') print('Click on the window after sorting finishes to select a new algorithm') command = input('\n') elif command == 'bubble': valid_command = True elif command == 'cocktail': valid_command = True elif command == 'comb': valid_command = True elif command == 'oddeven': valid_command = True elif command == 'insertion': valid_command = True elif command == 'shell': valid_command = True elif command == 'gnome': valid_command = True elif command == 'merge': valid_command = True elif command == 'quick': valid_command = True elif command == 'selection': valid_command = True elif command == 'stooge': valid_command = True elif command == 'quit': win.close() return else: print('Command not found - type help to view commands') command = input('\n') sort.playback_list.append(ds[:]) if command == 'insertion': sort.insertion_sort(ds) elif command == 'bubble': sort.bubble_sort(ds) elif command == 'cocktail': sort.cocktail_sort(ds) elif command == 'selection': sort.selection_sort(ds) elif command == 'merge': sort.merge_sort(ds, 0, sort.DATA_NUM - 1) elif command == 'quick': sort.quick_sort(ds, 0, sort.DATA_NUM - 1) elif command == 'shell': sort.shell_sort(ds) elif command == 'gnome': sort.gnome_sort(ds) elif command == 'oddeven': sort.odd_even_sort(ds) elif command == 'comb': sort.comb_sort(ds) elif command == 'stooge': sort.stooge_sort(ds, 0, sort.DATA_NUM - 1) sort.playback_list = remove_duplicates(sort.playback_list) play_animation(ds, win, bars) win.getMouse()
def test_selection_sort(): arr = [4, 3, 9, 2, 8, 1, 2, 0, 2] assert selection_sort(arr) == sorted(arr)
def test_unsorted_list(self): l = [5, 6, 3, 0, 1] selection_sort(l) self.assertEqual(l, [0, 1, 3, 5, 6])
def test_selection_sort(self): array = [7, 5, 1, 8, 3, 4, 4, 7, 3, 6, 2, 1, 8, 9, 0, 6] assert sort.selection_sort(array) == [0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9]
def test_case03(self): A = [3, 4, 5, 2, 1] print "origin A=%s" % A sort.selection_sort(A) print "selection sorted A=%s" % A self.assertTrue([1, 2, 3, 4, 5] == A)
def test_selection_sort(self): sorted_list = sort.selection_sort([5, 3, 8, 1, 10, 22, 15]) self.assertTrue(all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1)))
def test(n): data=generate_data(n) datas=[copy.deepcopy(data) for _ in range(7)] correct=generate_data(20) corrects=[copy.deepcopy(correct) for _ in range(7)] print("正确检测:") print("原始数据:",correct) sort.bubble_sort(corrects[0]) sort.insertion_sort(corrects[1]) sort.selection_sort(corrects[2]) sort.quick_sort(corrects[3],0,19) result=sort.merge_sort(corrects[4]) sort.shell_sort(corrects[5],2) sort.heap_sort(corrects[6]) print("冒泡排序:",corrects[0]) print("插入排序:",corrects[1]) print("选择排序:",corrects[2]) print("快速排序:",corrects[3]) print("归并排序:",result) print("希尔排序:",corrects[5]) print("堆排序:",corrects[6]) print() print("计算时间检测:") start=time.clock() sort.bubble_sort(datas[0]) end=time.clock() print("冒泡排序运行时间:",end-start) start=time.clock() sort.insertion_sort(datas[1]) end=time.clock() print("插入排序运行时间:",end-start) start=time.clock() sort.selection_sort(datas[2]) end=time.clock() print("选择排序运行时间:",end-start) start=time.clock() sort.quick_sort(datas[3],0,len(datas[3])-1) end=time.clock() print("快速排序运行时间:",end-start) start=time.clock() datas[4]=sort.merge_sort(datas[4]) end=time.clock() print("归并排序运行时间:",end-start) start=time.clock() sort.shell_sort(datas[5],2) end=time.clock() print("希尔排序运行时间:",end-start) start=time.clock() sort.heap_sort(datas[6]) end=time.clock() print("堆排序运行时间:",end-start) if datas[0]==datas[1]==datas[2]==datas[3]==datas[4]==datas[5]==datas[6]: print("测试通过!") else: print("测试失败!")