def medicao_tempo(lista_de_entradas): times = [] for entrada in lista_de_entradas: print("\n\n", len(entrada), "Entradas \n\n") sorters = [ BubbleSortPlus(entrada[:]), BubbleSort(entrada[:]), QuickSortPF(entrada[:]), QuickSort(entrada[:]), HeapSort(entrada[:]), InsertionSort(entrada[:]), MergeSort(entrada[:]), SelectionSort(entrada[:]), ShellSort(entrada[:]) ] #MEDINDO TEMPO DE ORDENAÇÃO for sorter in sorters: start = time.time() sorter.sort() end = time.time() tempo = end - start times.append([sorter.nome, len(entrada), tempo]) print("TEMPO", sorter.nome, len(entrada), "ENTRADAS:", tempo) return times
def MergeSortTime(m): etime = 0.0 createData(m) inputList = LinkedList.LinkedList(readInData()) eStartTime = time.time() e = SelectionSort.SelectionSort(inputList) eEndTime = time.time() eTime = eEndTime-eStartTime print("Recursive MergeSort : " + str(eTime))
def SelectionSortTime(m): dTime = 0.0 createData(m) inputList = LinkedList.LinkedList(readInData()) dStartTime = time.time() d = SelectionSort.SelectionSort(inputList) dEndTime = time.time() dTime = dEndTime-dStartTime print("SelectionSort : " + str(dTime))
def main(): l = randomList() print("List size: ", len(l)) #BubbleSort start = time.time() BubbleSort.bubbleSort(l) end = time.time() print("BubbleSort: ", end - start) #InsertionSort start = time.time() InsertionSort.insertionSort(l) end = time.time() print("InsertionSort: ", end - start) #SelectionSort start = time.time() SelectionSort.selectionSort(l) end = time.time() print("SelectionSort: ", end - start) #ShellSort start = time.time() ShellSort.shellSort(l) end = time.time() print("ShellSort: ", end - start) #MergeSort start = time.time() MergeSort.mergeSort(l) end = time.time() print("MergeSort: ", end - start) #QuickSort start = time.time() QuickSort.quickSort(l, 0, len(l) - 1) end = time.time() print("QuickSort: ", end - start)
def main(): inputList = [5, 7, 10, 4, 1, 3, 8, 6] outputList = [] print('\nA entrada é: ', inputList) print('\nOrdenando com InsertionSort...') outputList = IS.InsertionSort(inputList.copy()) print(outputList) print('\nOrdenando com SelectionSort...') outputList = SS.SelectionSort(inputList.copy()) print(outputList)
O = Util.generateSmallRange(sizeList[i]) #listList = [L, M, N, O] #listNames = ['Random', 'Sorted', 'Reversed', 'SmallRange'] listList = [L, M, O] listNames = ['Random', 'Sorted', 'SmallRange'] timesList = [[], [], [], [], [], [], []] for x in range(len(listList)): #L = listList[x] L = Util.generateList(sizeList[i]) A = QuickSort.QuickSort(L) B = HeapSort.HeapSort(L) C = InsertionSort.InsertionSort(L) D = MergeSort.MergeSort(L) E = PythonSorted.PythonSorted(L) F = SelectionSort.SelectionSort(L) G = RadixSort.RadixSort(L) sortList = [A, B, C, D, E, F, G] sortNames = [ 'Quick', 'Heap', 'Insertion', 'Merge', 'Python', 'Selection', 'Radix' ] #sortList = [C] #sortNames = ['Insertion'] for j in range(len(sortList)): Start = time.time() M = sortList[j].sort(L) runTime = (time.time() - Start) * 1000000
def test_CorrectInput(self): ''' Checks if input is correct. ''' output = SelectionSort.SelectionSort(123) self.assertEqual(output, -1)
def test_TestOutputArray(self): ''' Checks if array is sorted. ''' output = SelectionSort.SelectionSort([3, 4, 2, 5, 1]) self.assertEqual(output, [1, 2, 3, 4, 5])
# 测试所有的排序算法的效率 import random import sys import BubbleSort import InsertSort import MergeSort import QuickSort import SelectionSort import ShellSort import threading import copy if __name__ == '__main__': # 快速排序递归可能溢出,这里设置大一点的值 # sys.setrecursionlimit(1000000) ls = [i for i in range(1, 10001)] random.shuffle(ls) # 复制,否则前面的排序会影响到后面的计算 ls1 = copy.copy(ls) ls2 = copy.copy(ls) ls3 = copy.copy(ls) ls4 = copy.copy(ls) ls5 = copy.copy(ls) # 挨个运行 BubbleSort.bubbleSort(ls) SelectionSort.selectionSort(ls1) InsertSort.insertSort(ls2) ShellSort.shellSort(ls3) MergeSort.mergeSort(ls4) QuickSort.quickSort(ls5)
def test_reversed_input_list(self): self.assertTrue(SelectionSort.selection_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5])
def test_edge_case_empty_input_list(self): #Exepcted to return input_list as it is self.assertTrue(SelectionSort.selection_sort([]) == [])
import SelectionSort as ss lst = [] size = eval(input('Enter the size of the list: ')) for i in range(size): n = int(input('Enter the number: ')) lst.append(n) print('Before sorting list is: ', lst) ss.Selsort(lst) print('After sorting list is: ', lst)
arr19.append(tempVal) arr20.append(i) arr21.append(10 * N - i) numArray.append(tempVal) sortingTimeTableArray = [[ "Sorting Algorithm", "Random ", "Best ", "Worst" ]] # Selection sorted print("Selection sorted - Random Best Case Worst Case") selectionSortTimings = ["Selection Sort "] start = datetime.datetime.now() arr1 = SelectionSort(arr1) selectionSortTimings.append(str(datetime.datetime.now() - start)) start = datetime.datetime.now() arr2 = SelectionSort(arr2) selectionSortTimings.append(str(datetime.datetime.now() - start)) start = datetime.datetime.now() arr3 = SelectionSort(arr3) selectionSortTimings.append(str(datetime.datetime.now() - start)) sortingTimeTableArray.append(selectionSortTimings) # Insertion sorted print("Insertion sorted - Random Best Case Worst Case") insertionSortTimings = ["Insertion Sort "] start = datetime.datetime.now() arr4 = InsertionSort(arr4) insertionSortTimings.append(str(datetime.datetime.now() - start))
def sort_by_fitness(population): return SelectionSort.selection_sort_by_heuristic(population)
import SelectionSort lst = [3, 4, 1, 2, 0] SelectionSort.selectionSort(lst) print(lst)
import BucketSort def init(tabl, size): random.seed() for i in range(0, size): tabl.append(random.randrange(100)) tabl = [30] init(tabl, 30) print(tabl) print("Selection sort: \n") temp = SelectionSort.selectionSort(tabl) print(temp) print("\n\n") print("Insertion sort: \n") temp = InsertionSort.insertionSort(tabl) print(temp) print("\n\n") print("Bubble sort: \n") temp = BubbleSort.bubbleSort(tabl) print(temp) print("\n\n") print("Quick sort: \n") temp = QuickSort.quickSort(tabl)
print("Data yang di sort", list) print("Bubble Sort:") BubbleSort.bubblesort(list) print('=============================') import InsertionSort list = [2, 54, 38, 76, 23, 56, 84, 90] print('Data yang akan di sort :', list) print('Insertion Sort :') InsertionSort.insertion(list) print('=============================') import mergesort list = [2, 5, 60, 43, 27, 10, 89, 17] print('Data yang akan di sort :', list) print('Merge Sort :') mergesort.ms(list) print('=============================') import quickshort a = [68, 90, 78, 44, 34, 20, 100, 56, 34, 2] print('Data yang akan di sort :', list) print('Quick Sort :') quickshort.quickshort(a, 0, len(a) - 1) print('=============================') import SelectionSort lis = [54, 26, 93, 17, 77, 31, 44, 55, 20, 21, 34, 65, 70] print('Data yang akan di sort :', list) print('Selection Sort :') SelectionSort.selection(list) print('=============================')
# we have a data set starting with the very basic happy path to complex data = { "data1": range(10000) #Large sorted array } #-----------------------------------------------------------------------------# # BRUTE FORCE SORTING # #-----------------------------------------------------------------------------# # SELECTION SORTING for i in range(len(data)): # invoke the start time to measure the performance start_time = time.time() # Calling selection_sort for each data set SelectionSort.selection_sort(data["data" + str(i + 1)]) print("Selection time for data" + str(i + 1) + " = " + str(time.time() - start_time)) # BUBBLE SORTING for i in range(len(data)): # invoke the start time to measure the performance start_time = time.time() # Calling bubble_sort for each data set BubbleSort.bubble_sort(data["data" + str(i + 1)]) print("Bubble time for data" + str(i + 1) + " = " + str(time.time() - start_time)) #-----------------------------------------------------------------------------# # DECREASE AND CONQUER # #-----------------------------------------------------------------------------#
def testa_lista2(a, b, c, d, f, g): assert SelectionSort.ordena([1, 6, 2, 4, 7, 3]) == (1, 2, 3, 4, 6, 7)
def test_edge_case_one_item_input_list(self): #Expected to return input_list as it is self.assertTrue(SelectionSort.selection_sort([1]) == [1])
def testa_lista3(a, b, c, d, f, g): assert SelectionSort.ordena([10, 30, 20, 60, 50, 40]) == (10, 20, 30, 40, 50, 60)
def test_random_input_list(self): self.assertTrue(SelectionSort.selection_sort([5, 3, 7, 2]) == [2, 3, 5, 7])
def testa_lista4(a, b, c, d, f, g): assert SelectionSort.ordena([1, -2, 3, 4, 5, 6]) == (-2, 1, 3, 4, 5, 6)
start = time.time() BubbleSort.bubble_sort(test_list) finish = time.time() print("********************************") print("BubbleSort: ", test_list) print("time: %f" % (finish - start)) print("\n") test_list = [ 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67 ] start = time.time() SelectionSort.selection_sort(test_list) finish = time.time() print("********************************") print("SelectionSort: ", test_list) print("time: %f" % (finish - start)) print("\n") test_list = [ 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67 ] start = time.time() InsertionSort.insertion_sort(test_list) finish = time.time()
def testa_lista1(): assert SelectionSort.ordena([1, 2, 3, 4, 5, 6]) == (1, 2, 3, 4, 5, 6)
def test_TestOneDigitArray(self): ''' Checks if function does not return error for one digit. ''' output = SelectionSort.SelectionSort([3]) self.assertEqual(output, [3])
# Метод по созданию случайных списков def make_random_list(list_range): empty_list = [] for x in range(list_range): empty_list.append(random.randrange(0, list_range)) return empty_list # Создаем наши списки и помещаем их в другой список для более удобного взаимодействия с ними listOfLists = [] listOfLists.insert(0, make_random_list(100)) listOfLists.insert(1, make_random_list(1_000)) listOfLists.insert(2, make_random_list(10_000)) listOfLists.insert(3, make_consistent_list(100)) listOfLists.insert(4, make_consistent_list(1_000)) listOfLists.insert(5, make_consistent_list(10_000)) # Начинаем сортировать списки counter = 0 for i in listOfLists: if counter == 0: print("\n##### Random Lists #####") elif counter == 3: print("\n\n##### Consistent Lists #####") else: print("----------") print(bubbleSort(i.copy())) print(insertionSort(i.copy())) print(SelectionSort(i.copy())) counter += 1
MergeSort.metricas_mergesort(sorted(vetor, key=int, reverse=True), "decrescente") print(vetor) elif tipo == "6": print(vetor) QuickSort.metricas_quicksort_central(vetor, 0, len(vetor)-1, "aleatório") QuickSort.metricas_quicksort_central(sorted(vetor, key=int), 0, len(vetor)-1, "crescente") QuickSort.metricas_quicksort_central(sorted(vetor, key=int, reverse=True), 0, len(vetor)-1, "decrescente") print(vetor) elif tipo == "7": print(vetor) QuickSort.metricas_quicksort_primeiro(vetor, 0, len(vetor)-1, "aleatório") QuickSort.metricas_quicksort_primeiro(sorted(vetor, key=int), 0, len(vetor)-1, "crescente") QuickSort.metricas_quicksort_primeiro(sorted(vetor, key=int, reverse=True), 0, len(vetor)-1, "decrescente") print(vetor) elif tipo == "8": print(vetor) SelectionSort.metricas_selectionSort(vetor, "aleatório") SelectionSort.metricas_selectionSort(sorted(vetor, key=int), "crescente") SelectionSort.metricas_selectionSort(sorted(vetor, key=int, reverse=True), "decrescente") print(vetor) elif tipo == "9": print(vetor) ShellSort.metricas_shellsort(vetor, "aleatório") ShellSort.metricas_shellsort(sorted(vetor, key=int), "crescente") ShellSort.metricas_shellsort(sorted(vetor, key=int, reverse=True), "decrescente") print(vetor) else: print("Valor inválido") if input("\nDeseja ordernar o mesmo vetor com outra método? (1 - Sim ou 2 - Não): ") != '1': break
import QuickSort import MergeSort import InsertionSort import SelectionSort if __name__ == '__main__': l = [2, 7, 3, 1, 0, 11, 9, 8] QuickSort.quickSort(l) MergeSort.mergeSort(l) InsertionSort.insertionSort(l) SelectionSort.selectionSort(l) print(l)
def sort_by_fitness(population, data): m = lambda x: TSP.tourcost(data, x) return SelectionSort.selection_sort_by_func(population, m)
# -*- coding: utf-8 -*- """ Created on Fri Aug 12 21:54:23 2016 @author: BoXiao """ import SelectionSort def mergesort(l1, l2): li = [] i, j = 0, 0 while i < len(l1) and j < len(l2): if l1[i] < l2[j]: li.append(l1[i]) i += 1 else: li.append(l2[j]) j += 1 li += l1[i:] li += l2[j:] return li l1 = SelectionSort.selectionsort([2, 8, 3, 2, 6]) l2 = SelectionSort.selectionsort([1, 9, 3, 1, 34, 0]) print mergesort(l1, l2)
import time if __name__ == "__main__": sys.setrecursionlimit(6000) if len(sys.argv) == 2: ldata = ["n100terbalik.dat", "n100urut.dat"] for i in ldata: print("=========================") print("WORST CASE") if i == "n100terbalik.dat" else print( "BEST CASE") arr = List.LoadList(i) print("Banyak data : {}".format(len(arr))) # iterative section start = timeit.default_timer() SelectionSort.selectionSortIterative(arr) execution.calulate("Iterative selection sort", start) # recursive section arr = List.LoadList(i) start = timeit.default_timer() SelectionSort.selectionSortRecursive(arr, 0, len(arr)) execution.calulate("Recursive selection sort", start) else: ldata = ["n10.dat", "n100.dat", "n500.dat", "n1000.dat", "n1500.dat"] for i in ldata: print("=========================") arr = List.LoadList(i) print("Banyak data : {}".format(len(arr))) # iterative section
if num != "X": LI.append(int(num)) else: terminate = True print "\nThe Entered List is: ", LI print "\nPlease Choose any one of the following Sorting Algorithms: \n1.Bubble Sort \n2.Selection Sort \n3.Insertion Sort \n4.Quick Sort \n5.Merge Sort" choice = int(raw_input(">>")) if choice == 1: print "\nSorting the List using Bubble Sort..." BubbleSort.BubbleSort(LI) elif choice == 2: print "\nSorting the List using Selection Sort..." SelectionSort.SelectionSort(LI) elif choice == 3: print "\nSorting the List using Insertion Sort..." InsertionSort.InsertionSort(LI) elif choice == 4: print "\nSorting the List using Quick Sort..." QuickSort.QuickSort(LI) elif choice == 5: print "\nSorting the List using Merge Sort..." MergeSort.MergeSort(LI) else: print "\nSorry Wrong Selection!!!" print "BYE!!!" exit() print "\nThe Sorted List is : ", LI, "\n"