def extract( B, A ): idx = 0 for i in range(0, len(B) ): insertionsort( B[i], 0, len(B[i]) ) for m in range(0,len(B[i])): A[idx] = B[i][m] idx += 1
def main(): # Aumenta o limite de recursão padrão sys.setrecursionlimit(10**6) # Flag que mantém o loop principal executando = True # Loop principal while executando: print("Digite o número do diretório:") print(" 1 |\t./1000/") print(" 2 |\t./2000/") print(" 3 |\t./3000/") print(" 4 |\t./5000/") print(" |") print(" 0 |\tSAIR DO PROGRAMA") folder = int(input()) print() if folder == 0: print("FINALIZANDO EXECUÇÃO...") executando = False continue elif folder > 0 or folder < 5: print("Digite o numero do arquivo:") print(" 1 |\t./crescente.csv") print(" 2 |\t./decrescente.csv") print(" 3 |\t./random.csv") print(" |") print(" 0 |\tVOLTAR") file_index = int(input()) print() if file_index == 0: continue elif file_index < 0 or file_index > 3: print("Opção inválida.") else: print("Digite a opção do algoritmo de ordenação") print(" 1 |\tInsertion Sort") print(" 2 |\tMerge Sort") print(" 3 |\tQuick Sort") print(" 4 |\tSelection Sort") print(" |") print(" 0 |\tMENU INICIAL") algo = int(input()) print() if algo == 0: continue elif algo < 0 or algo > 4: print("Opção inválida") continue else: print("Opção inválida.") file_name = "datasets_prontos/" if folder == 1: file_name += "1000/" elif folder == 2: file_name += "2000/" elif folder == 3: file_name += "3000/" else: file_name += "5000/" if file_index == 1: file_name += "crescente.csv" elif file_index == 2: file_name += "decrescente.csv" else: file_name += "random.csv" with open(Path(file_name)) as file: data = list(DictReader(file)) tempo_total = 0 if algo == 1: start_time = time.time() data = insertionsort.insertionsort(data) tempo_total = (time.time() - start_time) elif algo == 2: start_time = time.time() mergesort.mergesort(data, 0, len(data)) tempo_total = (time.time() - start_time) elif algo == 3: start_time = time.time() Quick_Sort2.quicksort(data) tempo_total = (time.time() - start_time) else: start_time = time.time() selectionsort.selectionsort(data) tempo_total = (time.time() - start_time) header = data[0].keys() rows = [x.values() for x in data] print( "\n##############################################################################################" ) print(tabulate(rows, header)) print( "##############################################################################################\n" ) print( "Concluído em {} segundos, com {} comparações e {} movimentações." .format(tempo_total, metrics.comp, metrics.mov)) # Zera os valores das metricas metrics.resetmetrics()
import heapsort as hs import quicksort as qs import insertionsort as ins import random import time start = time.time() n = random.randrange(0, 100000) arr = [random.randrange(0, 100000) for x in range(n)] arr1 = arr.copy() # Heapsort arr2 = arr.copy() # Quicksort with random pivot arr3 = arr.copy() # Quicksort with fixed pivot arr4 = arr.copy() # Insertion sort print("[~] Generating {:} numbers took {:} s".format(n, time.time() - start)) start = time.time() hs.heapsort(arr1) print("[~] Heapsort took {:} s".format(time.time() - start)) start = time.time() qs.quicksort(arr2, 0, len(arr2) - 1, True) print("[~] Quicksort with random pivot took {:} s".format(time.time() - start)) start = time.time() qs.quicksort(arr3, 0, len(arr2) - 1) print("[~] Quicksort took {:} s".format(time.time() - start)) start = time.time() ins.insertionsort(arr4) print("[~] Insertion sort took {:} s".format(time.time() - start))
import insertionsort import time # The way I read files from a folder is learned from this website: https://blog.csdn.net/LZGS_4/article/details/50371030 dir_data = os.listdir("/Users/lucifer.w/Documents/573/Assignment2/DataSet") os.chdir("/Users/lucifer.w/Documents/573/Assignment2/DataSet") h_list = [7, 3, 1] for file in dir_data: datalist1 = [] # For insertion sort, you can also change the h_list to [1], then the shell sort will become insertion sort datalist2 = [] print(file) # Display the file that we are currently processing f = open(file, "r") f_line = f.readlines() for line in f_line: datalist1.append(line.strip()) datalist2.append(line.strip()) datalist1 = list(map(int, datalist1)) datalist2 = list(map(int, datalist2)) start_time1 = time.time() shellsort.shellsort(datalist1, h_list) spent_time1 = time.time() - start_time1 print("The runtime cost is", spent_time1) start_time2 = time.time() insertionsort.insertionsort(datalist2) spent_time2 = time.time() - start_time2 print("The runtime cost is", spent_time2)
from mergesort import mergesort from insertionsort import insertionsort import time from random import randint def create_random_array(size): return [randint(0, 2 * size) for _ in range(size)] RUNS = 25 for size in range(5, 501, 5): avg = 0 current_runs = 0 for _ in range(RUNS): a = create_random_array(size) start = time.clock() insertionsort(a) time_passed = time.clock() - start avg = avg * current_runs + time_passed current_runs += 1 avg /= current_runs print(size, avg)
def test_insertionsort_sorts_list(): """Test insertionsort sorts list of vals.""" from insertionsort import insertionsort unsorted_list = [6, 4, 7, 9, 0, 2] assert insertionsort(unsorted_list) == [0, 2, 4, 6, 7, 9]
from test_utilities import compare_arr_sorted_equal, summarize_results from time import clock from insertionsort import insertionsort GLOBAL_PRINT_DEBUG = False if __name__ == "__main__": runtime = [] results = [] print "####################################################" print("Test case 1") data = [1, 5, 3, 6, 10, 9, 4] result = data[:] time1 = clock() insertionsort(result) time2 = clock() print "runtime: ", time2 - time1 runtime.append(time2 - time1) output = compare_arr_sorted_equal(data, result) print(output) results.append(output) print "####################################################" print("Test case 2") data = [0, 999, 1000, 10, 100, 500, 300, 35, 598, 456, 985, 874] result = data[:] time1 = clock() insertionsort(result) time2 = clock() print "runtime: ", time2 - time1 runtime.append(time2 - time1)
def test_insertionsort_sorts_list(): """Test insertionsort sorts list of vals.""" from insertionsort import insertionsort unsorted_list = [3, 4, 2, 1, 5, 19] assert insertionsort(unsorted_list) == [1, 2, 3, 4, 5, 19]
def test_insertionsort(s): assert sorted(s) == insertionsort.insertionsort(s)
def test_insertionsort(self): self.assertEqual(insertionsort([1, 7, 5, 8, 2, 3, 4]), [1, 2, 3, 4, 5, 7, 8])
if __name__ == "__main__": import sys #from quicksort import quicksort from insertionsort import insertionsort if (len(sys.argv) < 2): print "please tyoe a few numbers after test_sort.py and I will sort them" #print 'Argument List:', str(sys.argv) lst = map(int, sys.argv[1:]) # Get typed numbers as list #print quicksort(lst) # print out the sorted list as a list print insertionsort(lst) import string #print string.join(map(str,quicksort(lst) )) # Print as a string print string.join(map(str, insertionsort(lst))) # Print as a string
def showbox(): for widget in self.winfo_children(): widget.destroy() x = int(n) label = Label(self, text="Enter the inputs in the array:", bg='black', fg='white', font='Georgia 24 bold', pady=10) label.grid(row=0, columnspan=x) ent20 = [] for i in range(0, x): entry = Entry(self, width=2, font=('Times', 28)) entry.grid(row=1, column=i, padx=5, pady=10) ent20.append(entry) def input1(): for i in range(0, x): risk.append(int(ent20[i].get())) btn = Button(self, text="SUBMIT", font='Times 17 bold', padx=30, pady=10, command=lambda: [input1(), insertionsort.insertionsort()]) btn.grid(row=3, columnspan=x, pady=70)
#!/usr/bin/env python import sys import random from timeit import timeit from bubblesort import bubblesort from mergesort import mergesort from quicksort import quicksort from insertionsort import insertionsort from gnomesort import gnomesort from selectionsort import selectionsort from heapsort import * #elements = sys.argv[1:] ## we need ints, not strings #elements = list(map(int, elements)) elements = [ random.randint(1,20) for _ in range(20) ] print(elements) print(bubblesort(elements[:])) print(mergesort(elements[:])) print(quicksort(elements[:])) print(insertionsort(elements[:])) print(gnomesort(elements[:])) print(selectionsort(elements[:])) print(heapsort(elements[:]))
def insertion(array): result = IS.insertionsort(array, [0, 0]) return result
def testinsertion(a,i,k): started = time_ns() insertionsort(a) ended = (time_ns() - started) outputfile(i,k,'insertion',ended)
# BubbleSort start = timer() bubblesort() end = timer() bubblesort_elapsed_time = end - start # HeapSort start = timer() heapsort() end = timer() heapsort_elapsed_time = end - start # InsertionSort start = timer() insertionsort() end = timer() insertion_elapsed_time = end - start # MergeSort start = timer() mergesort() end = timer() mergesort_elapsed_time = end - start # QuickSort start = timer() quicksort() end = timer() quicksort_elapsed_time = end - start
if __name__ == "__main__": import sys # from quicksort import quicksort from insertionsort import insertionsort if len(sys.argv) < 2: print "please tyoe a few numbers after test_sort.py and I will sort them" # print 'Argument List:', str(sys.argv) lst = map(int, sys.argv[1:]) # Get typed numbers as list # print quicksort(lst) # print out the sorted list as a list print insertionsort(lst) import string # print string.join(map(str,quicksort(lst) )) # Print as a string print string.join(map(str, insertionsort(lst))) # Print as a string
from bubblesort import bubblesort from mergesort import mergesort from insertionsort import insertionsort #int array from user input try: testarray = [] print("Type in a array, press any key other than a number to submit array") while True: testarray.append(int(input())) except: print("You entered: ", testarray) #sort method from user input method = input( "Choose a sorting method: \n(b)ubblesort \n(m)ergesort \n(i)nsertionsort \n" ) if method == "b": print("Array bubblesorted: ", bubblesort(testarray)) elif method == "m": print("Array mergesorted: ", mergesort(testarray)) elif method == "i": print("Array insertsorted: ", insertionsort(testarray)) else: print("That wasn't an option!")
def main(): args = sys.argv dataPath = os.path.abspath('../data/') outputPath = os.path.abspath('../output/') dataset = [ "data_10e0.csv", "data_10e1.csv", "data_10e2.csv", "data_10e3.csv", "data_10e4.csv", "data_10e5.csv", "data_25e0.csv", "data_25e1.csv", "data_25e2.csv", "data_25e3.csv", "data_25e4.csv", "data_25e5.csv", "data_50e0.csv", "data_50e1.csv", "data_50e2.csv", "data_50e3.csv", "data_50e4.csv", "data_50e5.csv", "data_75e0.csv", "data_75e1.csv", "data_75e2.csv", "data_75e3.csv", "data_75e4.csv", "data_75e5.csv" ] algorithm = args[1] csvIn = args[2] csvOut = args[3] if csvIn not in dataset: return print("Arquivo de entrada inválido.") arqIn = open(dataPath + '/' + csvIn, 'r') arqOut = open(outputPath + '/' + csvOut, 'w+') print("Processando arquivo...") csvData = arqIn.readline() csvData = arqIn.readlines() array = fillArray(csvData) print("Iniciando ordenação") start = time.time() if algorithm == "selectsort": array = selectionsort(array, compare) elif algorithm == "insertsort": array = insertionsort(array, compare) elif algorithm == "mergesort": array = mergesort(array, compare) elif algorithm == "quicksort": array = quicksort(array, compare) elif algorithm == "heapsort": array = heapsort(array, compare) elif algorithm == "introsort": array = introsort(array, compare) elif algorithm == "patiencesort": array = patiencesort(array, compare) else: return print("Algoritmo inválido.") end = time.time() print("Fim da ordenação") print(algorithm + " " + str(len(csvData)) + " " + str((end - start) * 1000) + "\n") print("Escrevendo csv...") for p in array: arqOut.write(p.email + ",") arqOut.write(p.gender + ",") arqOut.write(p.uid + ",") arqOut.write(p.birthdate + ",") arqOut.write(p.height + ",") arqOut.write(p.weight) arqOut.close() arqIn.close()