def testHeapsort( self ): A = [8, 5, 3, 1, 9, 6, 0, 7, 4, 2, 5] sorting.heapsort( A ) heapsort.heapsort( A ) for i in range( 1, len( A ) ): if A[i - 1] > A[i]: self.fail( "heapsort method fails." )
def kruskal(self, G): minimum_spanning_tree = graph.Graph() for vid in G.vertList.keys(): self.make_set(vid) minimum_spanning_tree.addVertex(vid) G.collectEdges() #G.showEdge() edges = G.getEdgeList() #print('edges:') #print(edges) startTime = time.time() #edges.sort() heapsort.heapsort(edges) elaspedTime = time.time() - startTime print('edge sort elaspedTime: %f' % elaspedTime) #print('sorted edges:') #print(edges) for edge in edges: weight, vertice1, vertice2 = edge if self.find(vertice1) != self.find(vertice2): self.union(vertice1, vertice2) minimum_spanning_tree.addEdge(vertice1, vertice2, weight) self.mst = minimum_spanning_tree return minimum_spanning_tree
def test_heapsort(self): for j in range(NUM_TESTS): l = rand_list(max_list=MAX_LIST) # no return! heapsort(l) for i in range(0, len(l) - 1): self.assertLessEqual(l[i], l[i + 1])
def adasort_helper(l, start, end, depth): if end <= start + 16: insertion_sort(l, start, end) elif depth == 0: heapsort(l, start, end) else: bls = hoare_partition(l, start, end) adasort_helper(l, start, bls, depth - 1) adasort_helper(l, bls + 1, end, depth - 1)
def test_heapsort(self): self.assertRaises(TypeError, heapsort, (1, 2, 3)) self.assertRaises(TypeError, heapsort, 1) self.assertRaises(TypeError, heapsort, 'helloworld!') random.shuffle(self.seq) self.seq = heapsort(self.seq) self.assertEqual(self.seq, range(self.N))
def main(): """Return the sorted list, using the correct algorithm """ parser = argparse.ArgumentParser(description='Sort an array.') parser.add_argument('--algorithm', dest='algorithm', default='heapsort', help='quicksort or heapsort (default: heapsort)') args = parser.parse_args() sortable = sys.stdin.readlines() if len(sortable) == 0: return if args.algorithm == 'heapsort': heapsort(sortable) elif args.algorithm == 'quicksort': quicksort(sortable) else: err = 'The only valid algorithm options are heapsort or quicksort.' print(err, file=sys.stderr) return out = ''.join(sortable) print(out.rstrip('\n'))
def introsort(array, compare): size = len(array) max_depth = math.log(size, 2) pivot = size - 1 if size < 2: return elif pivot > max_depth: array = heapsort(array, compare) return array before = introsort(array[:pivot], compare) after = introsort(array[pivot + 1:], compare) before.append(array[p]) return before + after
def introsort(a, maxdepth): if len(a) <= 1: return a elif maxdepth == 0: a = heapsort(a) return a else: pivot_index = randrange(0, len(a)) pivot_element = a[pivot_index] left = [ _ for i, _ in enumerate(a) if _ <= pivot_element and i != pivot_index ] right = [ _ for i, _ in enumerate(a) if _ > pivot_element and i != pivot_index ] left = introsort(left, maxdepth - 1) right = introsort(right, maxdepth - 1) left.append(pivot_element) left.extend(right) return left
sys.exit(-1) if __name__ == "__main__": main() A = vetor[1:] # primeiro elemento da lista eh o tamanho da lista n = vetor[0] if opt == 'SS': saida(selection_sort(A)) if opt == 'IS': saida(insertion_sort(A)) if opt == 'HS': saida(heapsort(A)) if opt == 'MS': saida(topDownMergeSort(A)) if opt == 'QS': saida(quickSort(A)) if opt == 'CS': saida(counting_sort(A)) if opt == 'RS': saida(radix_sort(A))
print('Quicksort (Lomuto)') n = [random.randint(0, 99) for _ in range(20)] print(n) snl = quicksort_lomuto(n) print(snl) assert(snl == sorted(n)) print() print('Quicksort (Hoare)') n = [random.randint(0, 99) for _ in range(20)] print(n) snh = quicksort_hoare(n) print(snh) assert(snh == sorted(n)) print() print('Heapsort') n = [random.randint(0, 99) for _ in range(20)] print(n) snheap = heapsort.heapsort(n) print(snheap) assert(snheap == sorted(n)) print() print('Mergesort') n = [random.randint(0, 99) for _ in range(20)] print(n) snm = mergesort.mergesort(n) print(snm) assert(snm == sorted(n))
def sort(self,items): heapsort(items)
CS = vetor[1:] RS = vetor[1:] # dicionario para armazenas o tempo de execucao tempo = {} # algoritmos start = time.time() selection_sort(SS) tempo['SS'] = (time.time() - start)*1000 start = time.time() insertion_sort(IS) tempo['IS'] = (time.time() - start)*1000 start = time.time() heapsort(HS) tempo['HS'] = (time.time() - start)*1000 start = time.time() quickSort(QS) tempo['QS'] = (time.time() - start)*1000 start = time.time() topDownMergeSort(MS) tempo['MS'] = (time.time() - start)*1000 start = time.time() CS, menorValor = entrada_NegaToPosi(CS, n) # deixa lista totalmente positiva CS = counting_sort(CS) CS = entrada_PosiToNega(CS, menorValor, n) # retorna a lista com valores original tempo['CS'] = (time.time() - start)*1000
def call_alg(): heapsort(A)
''' sort big random arrays in different amounts of time Nate Weeks February 2019 ''' import time import random from heapsort import heapsort from bubblesort import bubbleSort arr = [] for i in range(10000): arr.append(random.randint(1, 10000)) bBeginTime = time.time() bubbleSort(arr) bEndTime = time.time() arr = [] for i in range(10000): arr.append(random.randint(1, 10000)) hBeginTime = time.time() heapsort(arr) hEndTime = time.time() bubbletime = bEndTime - bBeginTime heaptime = hEndTime - hBeginTime print("bubble sort time on 10k items: {}".format(bubbletime)) print("heap sort time on 10k items: {}".format(heaptime))
def test_heapsort(self): inputs = [[], [1, 3, 2], [1, 4, 5, 6, 7, 9, 8, 2, 3, 0]] outputs = [[], [1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] for in_array, out_array in zip(inputs, outputs): self.assertEqual(heapsort(in_array), out_array)
from mergesort import mergesort from bubble_sort import bubble_sort from insertion_sort import insertion_sort from quicksort import quicksort from selection_sort import selection_sort from heapsort import heapsort import pprint def show(A): pprint.pprint(A) A = [ 'b', 'z', 'f', 'x', 'c', 'd', 'y', 'a', 'w', 'e'] #A = [ 5, 2, 1, 4, 6, 3 ] #A = [1,2,3,4,5,6,7] show(A) heapsort(A) show(A)
def test_heapsort(self): arr = [9, 3, 2, 5, 8, 4, 7, 10, 6, 1] arr = heapsort(arr) self.assertEqual(arr, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
from mergesort import mergesort from bubble_sort import bubble_sort from insertion_sort import insertion_sort from quicksort import quicksort from selection_sort import selection_sort from heapsort import heapsort import pprint def show(A): pprint.pprint(A) A = ['b', 'z', 'f', 'x', 'c', 'd', 'y', 'a', 'w', 'e'] #A = [ 5, 2, 1, 4, 6, 3 ] #A = [1,2,3,4,5,6,7] show(A) heapsort(A) show(A)
def test_heapsort(test_arr): sorted_arr = sorted(test_arr) my_arr = heapsort.heapsort(test_arr) if my_arr == sorted_arr: return True
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))
def test_heapsort(s): assert sorted(s) == heapsort.heapsort(s)
def test(self): from random import sample sequence = list(range(15)) shuffled = sample(sequence, len(sequence)) self.assertEqual(heapsort(shuffled), sequence)
sortMode = 1 elif argI == "-heap": sortMode = 2 fileName = argII print(fileName) fileContent = None with open(fileName) as file_obj: # testFile=open(fileName,'r') fileContent = file_obj.readlines() file_obj.close() except FileNotFoundError: print('File does not exists: ' + fileName) sys.exit(-1) del fileContent[0] #ignore the comment line for i in range(0, len(fileContent)): #parse into floats fileContent[i] = float(fileContent[i]) if sortMode == 1: quicksort(fileContent) elif sortMode == 2: heapsort(fileContent) for i in fileContent: print('%.5f' % i) sys.exit(0)
#!/usr/bin/python3 from bubblesort import bubblesort from heapsort import heapsort from insertionsort import insertionsort from mergesort import mergesort from quicksort1 import quicksort1 from quicksort2 import quickSort2 from selectionsort import selectionsort from shellsort import shellsort bubblesort() heapsort() insertionsort() mergesort() quicksort1() quickSort2() selectionsort() shellsort()
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()