def test_partitionExpectedTransformation2(self): array = [4, 5, 1, 0, 8, 4, 3, 7, 6] pivotI = 5 expected = [4, 1, 0, 3, 4, 6, 5, 7, 8] qs = QuickSort() result = qs.partition(array, pivotI) self.assertEqual(expected,result)
def _tempo_do_quick_sort_para_ordernar_a_lista(self, lista) -> float: quick_sort = QuickSort() start = timeit.default_timer() quick_sort.quick_sort(lista, 0, len(lista) - 1) end = timeit.default_timer() return end - start
def test_partitionWrongPivotIndex(self): size = r.randint(5,50) array = [r.randint(0,size) for i in xrange(size)] pivotIndex = size; qs = QuickSort() result = qs.partition(array, pivotIndex) self.assertEqual(array,result)
def sorted_merge_brute(A, B): y = 0 for i in range(len(A)): if A[i] is None: A[i] = B[y] y += 1 qs = QuickSort() qs.quick_sort(A) print(A)
def test_quicksort_1(): arr = [1,8,9,3,7,4,6,2,5] actual = QuickSort(arr) expected = [1,2,3,4,5,6,7,8,9] assert actual == expected
def test_quicksort_3(): arr = [79, 457, 39, 74, 20, 74, 29, 68, 270, 1] actual = QuickSort(arr) expected = [1, 20, 29, 39, 68, 74, 74, 79, 270, 457] assert actual == expected
def test_quicksort_2(): arr = [9,8,7,6,5,4,3,2,1] actual = QuickSort(arr) expected = [1,2,3,4,5,6,7,8,9] assert actual == expected
def __init__(self, array: List, value: int): a = array[:] QuickSort(a) self.result_first = self.search_first(a, value) self.result_last = self.search_last(a, value) self.result_first_greater_equal_to = self.search_first_greater_equal_to( a, value) self.result_last_smaller_equal_to = self.search_last_smaller_equal_to( a, value)
def zero_quadruplets_count(cls, first_seq, second_seq, third_seq, fourth_seq): fourth_seq = QuickSort.quick_sort(fourth_seq) quadrupletes = [] for num1 in first_seq: for num2 in second_seq: for num3 in third_seq: num4 = -(num1 + num2 + num3) if cls.binary_search(fourth_seq, num4) is not None: quadrupletes.append([num1, num2, num3, num4]) return len(quadrupletes)
def test_exchanger(self): qs = QuickSort() # A list of len <= 1 should return the list itself self.assertEquals(qs.exchanger(10, 10), None) self.assertEquals(qs.exchanger(10, 0), None) for trial in range(100): qs.array = [] for i in range(10000): qs.array.append(random.randrange(-100000, 100000)) copyqs = list(qs.array) copyqs.sort() qs.exchanger(0, 9999) self.assertEquals(qs.array, copyqs)
def run(): # orig_obj_values = [ "apple", "orange", "banana", "apple", "coconut", "olive", "egg", "banana", "ham", "milk", "coconut", "cheese" ] value_count = 10000 orig_obj_values = np.empty(shape=(value_count)) min = value_count + 1 max = -1 for i in range(value_count): # in c#, random.next(incl, excl), but in python, randint(incl, incl) v = random.randint(0, value_count - 1) if v < min: min = v if v > max: max = v orig_obj_values[i] = int(v) obj_values = np.empty_like(orig_obj_values) obj_values[:] = orig_obj_values algorithms = np.array([ BubbleSort(), SelectionSort(), InsertionSort(), QuickSort(), MergeSort(), CountingSort(min, max), HeapSort(), RadixSort() ]) print("Python") print("STARTED --------------------------------------------") for algorithm in algorithms: # reset input values obj_values[:] = orig_obj_values algorithm.run(obj_values) print(" ") print("STOPPED --------------------------------------------")
class QuickSortTester(unittest.TestCase): def setUp(self): self.qs = QuickSort() def test_partition(self): arr = [10, 5, 2, 90, 61, 32, 3] #pivot point is 10 #after partition array should be #[5, 2, 3, 10, 90, 61, 32] result = self.qs.partition(arr, 0, len(arr) - 1) self.assertEqual(arr[3], 10) self.assertTrue(arr[0] <= 10) self.assertTrue(arr[1] <= 10) self.assertTrue(arr[2] <= 10) self.assertTrue(arr[4] >= 10) self.assertTrue(arr[5] >= 10) self.assertTrue(arr[6] >= 10) def test_quick_sort(self): arr = [11, 5, 7, 2, 76, 31, 20, 3, 9] result = self.qs.quick_sort(arr) self.assertEqual(arr, [2, 3, 5, 7, 9, 11, 20, 31, 76]) def test_quick_sort_on_already_sorted_input(self): arr = [1, 2, 3, 4, 5] result = self.qs.quick_sort(arr) self.assertEqual(arr, result) def test_quick_sort_on_partially_sorted_array(self): arr = [1, 2, 10, 4, 90, 1001, 23] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2, 4, 10, 23, 90, 1001]) def test_quick_sort_on_single_element_array(self): arr = [9] result = self.qs.quick_sort(arr) self.assertEqual(result, [9]) def test_quick_sort_on_two_element_array(self): arr = [2, 1] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2]) arr = [1, 2] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2])
class QuickSortTester(unittest.TestCase): def setUp(self): self.qs = QuickSort() def test_partition(self): arr = [10, 5, 2, 90, 61, 32, 3] #pivot point is 10 #after partition array should be #[5, 2, 3, 10, 90, 61, 32] result = self.qs.partition(arr, 0, len(arr)-1); self.assertEqual(arr[3], 10) self.assertTrue(arr[0] <= 10) self.assertTrue(arr[1] <= 10) self.assertTrue(arr[2] <= 10) self.assertTrue(arr[4] >= 10) self.assertTrue(arr[5] >= 10) self.assertTrue(arr[6] >= 10) def test_quick_sort(self): arr = [11, 5, 7, 2, 76, 31, 20, 3, 9] result = self.qs.quick_sort(arr) self.assertEqual(arr, [2, 3, 5, 7, 9, 11, 20, 31, 76]) def test_quick_sort_on_already_sorted_input(self): arr = [1, 2, 3, 4, 5] result = self.qs.quick_sort(arr) self.assertEqual(arr, result) def test_quick_sort_on_partially_sorted_array(self): arr = [1, 2, 10, 4, 90, 1001, 23] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2, 4, 10, 23, 90, 1001]) def test_quick_sort_on_single_element_array(self): arr = [9] result = self.qs.quick_sort(arr) self.assertEqual(result, [9]) def test_quick_sort_on_two_element_array(self): arr = [2, 1] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2]) arr = [1, 2] result = self.qs.quick_sort(arr) self.assertEqual(result, [1, 2])
def main(): # Sort the following array: [43, 1, 32, 7, 12, 56, 2, 14] print('1. Test QuickSort algorithm') a = [43, 1, 32, 7, 12, 56, 2, 14] print('array before quicksort: {}'.format(a)) s = QuickSort() s.sort(list(a)) print('array after quicksort: {}\n'.format(s.numbers)) # Test runtimes print('2. Test runtimes') random.seed(0) array_size = 1000 dataset1 = [random.randint(0, array_size) for i in range(array_size)] dataset2 = sorted(dataset1) dataset3 = list(reversed(dataset2)) datasets = [dataset1, dataset2, dataset3] for pivot in ['middle', 'first', 'last', 'random']: print('Test quicksort with {} element as pivot'.format(pivot)) for i, dataset in enumerate(datasets): if i == 0: print('time if dataset unsorted:') if i == 1: print('time if dataset already sorted:') if i == 2: print('time if dataset sorted in reverse order:') times = [] for i in range(10): start = time.time() s = QuickSort(pivot=pivot) s.sort(list(dataset)) end = time.time() times.append(end - start) print(np.mean(times)) print('---------------')
def setUp(self): self.merge_sort = MergeSort() self.quick_sort = QuickSort()
def main(): check = Check() create = CreateRandomList() selectionSort = SelectionSort() bubbleSort = BubbleSort() insertionSort = InsertionSort() mergeSort = MergeSort() quickSort = QuickSort() heapSort = HeapSort() while True: system("cls") print(menu1) choice0 = input("Enter a number = ") if choice0 == "1": system("cls") small = int(input("Enter smallest number = ")) big = int(input("Enter biggest number = ")) length = int(input("Enter length = ")) if check.checkLength(length) == True and check.checkSmallBig(small, big) == True: aList = create.createList(small, big, length) print(createdList.format(aList), end="\n\n") while True: print(menu2) choice1 = input("Enter a number = ") if choice1 == "1": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") selectionSort.sort(tempList) input(string1) elif choice1 == "2": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") bubbleSort.sort(tempList) input("PRESS ENTER or ANY INPUT") elif choice1 == "3": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") insertionSort.sort(tempList) input("PRESS ENTER or ANY INPUT") elif choice1 == "4": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") mergeSort.sort(tempList) input("PRESS ENTER or ANY INPUT") elif choice1 == "5": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") quickSort.sort(tempList, 0, len(tempList)-1) input("PRESS ENTER or ANY INPUT") elif choice1 == "6": tempList = aList.copy() print(createdList.format(tempList), end="\n\n") heapSort.sort(tempList) input("PRESS ENTER or ANY INPUT") else: input("PRESS ENTER or ANY INPUT") elif choice0 == "0": quit()
def test_quicksort(self): qs = QuickSort() # Base case: empty list or list of one element should return itself self.assertEquals(qs.quicksort(), []) qs.array = [1] self.assertEquals(qs.quicksort(), [1])
def main(): """ Main method :return: """ s = QuickSort() num_list = read_in_list(input('Enter in location of file: ')) p_type = validate_pivot_type(input('Enter in which type of pivot you want to use: ')) if p_type == 'first': s.first_quicksort(num_list, 0, len(num_list) - 1) elif p_type == 'last': s.end_quicksort(num_list, 0, len(num_list) - 1) else: s.mid_quicksort(num_list, 0, len(num_list) - 1) print(num_list) print("Count: ") s.get_count() s.reset_count()
from Utils import Utils from QuickSort import QuickSort from MergeSort import MergeSort from InsertionSort import InsertionSort from SelectionSort import SelectionSort from BubbleSort import BubbleSort # QUICK SORT print("----- QUICK SORT -----\n") numbers = Utils.get_numbers() print("Unsorted numbers", numbers) print("Sorted numbers", QuickSort.sort(numbers)) characters = Utils.get_characters() print("Unsorted characters", characters) print("Sorted characters", QuickSort.sort(characters)) strings = Utils.get_strings() print("Unsorted strings", strings) print("Sorted stirngs", QuickSort.sort(strings)) # MERGE SORT print("\n----- QUICK SORT -----\n") numbers = Utils.get_numbers() print("Unsorted numbers", numbers) print("Sorted numbers", MergeSort.sort(numbers)) characters = Utils.get_characters()
def __init__(self, array: List, value: int): a = array[:] QuickSort(a) # self.result = self.search(a, value) self.result = self.search_recursive(a, value, 0, len(a) - 1)
def setUp(self): self.qs = QuickSort()
#Binary search from QuickSort import QuickSort def SearchElementInArray(arr, element, min, max): #Base case of recursion if max >= min: #Find the index of half array MidElement = min + (max - min) // 2 #If the element to find catch with "MidElement" return it if arr[MidElement] == element: return MidElement #if the element to find is less than element in "MidElement" index search just on the left way elif arr[MidElement] > element: return SearchElementInArray(arr, element, min, MidElement - 1) #else search just on the right way else: return SearchElementInArray(arr, element, MidElement + 1, max) else: return -1 if __name__ == '__main__': Arr = [14, 17, 16, 18, 6] x = 17 Sort = QuickSort(Arr) res = SearchElementInArray(Arr, x, 0, len(Arr) - 1) print(res)
def test_getpivot(self): qs = QuickSort() # Basic case, find middle of three, regardless of location in list qs.array = [1, 2, 3] self.assertEquals(qs.getpivot(0, 2), 2) qs.array = [2, 1, 3] self.assertEquals(qs.getpivot(0, 2), 2) qs.array = [1, 3, 2] self.assertEquals(qs.getpivot(0, 2), 2) # One-item list qs.array = [-7] self.assertEquals(qs.getpivot(0, 0), -7) # List of the same item repeated qs.array = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] self.assertEquals(qs.getpivot(0, 9), 2) # Find middle of three when they're the same and the list is longer qs.array = [10, 2, 2, 2, 10, 2, 2, 2, 2, 10] self.assertEquals(qs.getpivot(0, 9), 10) # Find middle of three when only two are the same qs.array = [10, 2, 2, 2, 10, 2, 2, 2, 2, 0] self.assertEquals(qs.getpivot(0, 9), 10) qs.array = [0, 2, 2, 2, 10, 2, 2, 2, 2, 10] self.assertEquals(qs.getpivot(0, 9), 10) qs.array = [10, 2, 2, 2, 0, 2, 2, 2, 2, 10] self.assertEquals(qs.getpivot(0, 9), 10)
from QuickSort import QuickSort L1 = [4, 1, 3, 6, 2, 8, 10, 40, 30, 11, 9] L2 = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] L3 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] obj = QuickSort(L2) print(obj.sort())
from QuickSort import QuickSort quick_sort = QuickSort() arr = [4, 5, 22, 4, 2, 1, 5, 7] quick_sort.sort(arr) print(arr)
from Bank import Bank from QuickSort import QuickSort from SelectionSort import SelectionSort if __name__ == "__main__": banks_list = [] name_pos = 0 clients_pos = 1 credits_pos = 2 file = open('banks_list.csv') for line in file: values = line.split(',') bank = Bank(values[name_pos], int(values[clients_pos]), int(values[credits_pos][:-1])) banks_list.append(bank) print("Selection sort:") selection_sort = SelectionSort(banks_list) start_time = time.clock() selection_sort.selection_sort() print("Time: " + str(time.clock() - start_time)) for bank in banks_list: print(bank) print("\nQUICK sort:") quick_sort = QuickSort(banks_list) start_time = time.clock() quick_sort.quick_sort() print("Time: " + str(time.clock() - start_time)) for bank in banks_list: print(bank)
values_add, values_min, values_max = elabora(BubbleSort(True), this_list, rounds, repetitions) print("BubbleSort(True) done!") values_quickbubble_add.append(values_add) values_quickbubble_min.append(values_min) values_quickbubble_max.append(values_max) values_add, values_min, values_max = elabora(BubbleSort(False), this_list, rounds, repetitions) print("BubbleSort(False) done!") values_bubble_add.append(values_add) values_bubble_min.append(values_min) values_bubble_max.append(values_max) values_add, values_min, values_max = elabora(QuickSort(), this_list, rounds, repetitions) print("QuickSort() done!") values_quicksort_add.append(values_add) values_quicksort_min.append(values_min) values_quicksort_max.append(values_max) values_add, values_min, values_max = elabora(BinarySearchTree(), this_list, rounds, repetitions) print("BinarySearchTree() done!") values_binarytree_add.append(values_add) values_binarytree_min.append(values_min) values_binarytree_max.append(values_max) values_add, values_min, values_max = elabora(HeapSort(), this_list, rounds, repetitions) print("HeapSort() done!")
def control_menu_Quicksort(self): opc2 = 0 # Inicializa opc2. cInterfaz = Interfaz() qs = QuickSort([6, 3, 2, 7, 5, 2, 4, 8, 777]) # Creo el objeto Interfaz. #___________________________________________________________ Inicio del ciclo while - Iterar menú. while ( opc2 != 7 ): # ///////////// Numero a poner el de la opcion SALIR /////////////////////// os.system('cls') # Limpia pantalla cInterfaz.menu_Quicksort() # Llama método externo. opc2 = int(input("\nIngrese la opcion: ") ) # Aquí almacenamos en opc2 lo que digite el usuario. #------------------------------------------------------- Bloque de evaluación para menu quicksort. if opc2 == 1: os.system("cls") print("---- Creando Lista ----") a = self.crearLista() qs.setQ(a) elif opc2 == 2: os.system("cls") print("---- Ordenando Lista ----") qs.quickSortRandom(qs.Q, 0, len(qs.Q) - 1) print(qs.Q) input("\nPresione TECLA para continuar...") elif opc2 == 3: os.system("cls") print("---- Ordenando Lista ----") qs.quickSort(qs.Q, 0, len(qs.Q) - 1) print(qs.Q) input("\nPresione TECLA para continuar...") elif opc2 == 4: os.system("cls") print("---- Timing del QuickSort ----") qs.timing_quickSort_Rand() input("\nPresione TECLA para continuar...") elif opc2 == 5: os.system("cls") print("---- Timing del QuickSort ----") qs.timing_quickSort() input("\nPresione TECLA para continuar...") elif opc2 == 6: os.system("cls") print("---- Guardadndo csv del QuickSort ----") qs.quickSort_rand_time_save() qs.quickSort_time_save() input("\nPresione TECLA para continuar...") #qs.quickSort() #------------------------------------------------------- Fin bloque de evaluación. #_______________________________________________________ Fin bloque while. pass
start_time = timeit.default_timer() sortObject.sort(input) elapsed = timeit.default_timer() - start_time return elapsed * 100 #Input Sizes inputSizes = [ 1000, 2000, 5000, 10000, 20000, 25000, 40000, 50000, 60000, 75000, 100000 ] #Creating objects of sorting implementation and data Creation utility data = CreateDataUtility() insertionSort = InsertionSort() mergeSort = MergeSort() quickSort = QuickSort() modifiedQuickSort = ModifiedQuickSort() #Creating a csv file with results in "Results/" folder with open('Results/Running-times-average-case.csv', mode='w') as csv_file: writer = csv.writer(csv_file, delimiter=',') writer.writerow(['Sort Algorithm', 'input Size', 'Time Taken']) for inputSize in inputSizes: input = data.CreateAverageCaseData(inputSize) sys.setrecursionlimit(max(sys.getrecursionlimit(), len(input) + 50000)) insertionSortInput = [] insertionSortInput.extend(input) mergeSortInput = [] mergeSortInput.extend(input) quickSortInput = [] quickSortInput.extend(input)
#!/usr/bin/env python """A little test-suite for me to test the speeds of algorithms. """ from timeit import timeit from random import randrange from InsertionSort import InsertionSort from BubbleSort import BubbleSort from QuickSort import QuickSort from MergeSort import MergeSort TIMES = 1 SORT_COUNT = 10001 dataset = [randrange(1, 1000) for _ in range(SORT_COUNT)] insertionsort_time = timeit(lambda: InsertionSort(dataset), number=TIMES) bubblesort_time = timeit(lambda: BubbleSort(dataset), number=TIMES) quicksort_time = timeit(lambda: QuickSort(dataset), number=TIMES) mergesort_time = timeit(lambda: MergeSort(dataset), number=TIMES) print(f"Sorted {SORT_COUNT - 1} integers.") print( f"Execution time of InsertionSort, executed {TIMES} times: {insertionsort_time}" ) print( f"Execution time of Bubblesort, executed {TIMES} times: {bubblesort_time}") print(f"Execution time of QuickSort, executed {TIMES} times: {quicksort_time}") print(f"Execution time of MergeSort, executed {TIMES} times: {mergesort_time}")