def testquicksort(self): items = [random.randint(-100,100) for c in range(10000)] print("before sort ",items) QuickSort.sort(items) print("after sort ", items) for i in range(len(items)-1): if(items[i] > items[i+1]): self.fail("Quick sort failed!")
def test_merge_sort_empty_array(self): array = random.sample(range(1, 100), 0) array_duplicate = array[:] quick = QuickSort(array) self.assertIsNotNone(quick.array) self.assertEqual(len(quick.array), 0) array_duplicate.sort() quick.quick_sort_algorithm(0, len(quick.array) - 1) self.assertEqual(quick.array, array_duplicate)
def test_merge_odd_number_elements(self): array = random.sample(range(1, 100), 9) array_duplicate = array[:] quick = QuickSort(array) self.assertIsNotNone(quick.array) self.assertEqual(len(quick.array), 9) array_duplicate.sort() self.assertNotEqual(quick.array, array_duplicate) quick.quick_sort_algorithm(0, len(quick.array) - 1) self.assertEqual(quick.array, array_duplicate)
def test_quick_sort(self) -> None: elements: List[int] = [] #random.seed(a=1) elements = [random.randrange(0, 101) for _ in range(100)] #elements = [75, 10, 92, 92, 35] print('Elements are :{}'.format(elements)) qs = QuickSort() sorted_elements = qs.sort(elements) print('Elements after sorting are : {}'.format(elements)) elements.sort() self.assertEqual(elements, sorted_elements)
def run_quick_sort(): ll = list(np.random.randint( -10, 10, 15)) # [7, 6, 5, 4, 3, 2, 1] # np.random.randint(-10, 10, 10)# print(ll) qs = QuickSort(ll) res = qs.sort() print("QuickSort") print() print(f"before: {ll}") print(f"after: {res}") print()
def test_bin_search(test_args, expected): """The list is first sorted with a custom quick search, then a binary search occurs param: n - Length of entered list (int) param: b_search - result of binary search """ print(test_args) n = len(test_args) - 1 test_sort = QuickSort() test_sort.quickSort(test_args, 0, n) b_search = BinarySearch().bin_search(test_args, 12) assert b_search == expected
def do_sort_user(self, key=None): """sort user table with desired key""" if hasattr(self, 'user_data'): if key is None: key = input("Enter a field through which you want to sort :") else: key = key sort_obj = QuickSort() result_set = sort_obj.resultset(self.user_data) sorted_data = sort_obj.sort(result_set, key=key) self.__class__.print_func(self, sorted_data) print(f"Sorted using {key}") else: self.do_all_users(self) self.do_sort_user(key=key)
def BucketSort(nums, defaultBucketSize=100): """ 桶排序 :param nums: 输入的待排序数组 :param defaultBucketSize: 桶数目,不指定时为5 :return: inplace 操作 """ maxVal, minVal = max(nums), min(nums) bucketSize = defaultBucketSize # 如果没有指定桶的大小,则默认为5 bucketCount = ((maxVal - minVal) // bucketSize) + 1 # 数据分为 bucketCount 组 buckets = [] # 二维桶 for i in range(bucketCount): buckets.append([]) # 利用函数映射将各个数据放入对应的桶中 for num in nums: buckets[(num - minVal) // bucketSize].append(num) nums.clear() # 清空 nums # print(buckets) # 对每一个二维桶中的元素进行排序 for bucket in buckets: QuickSort(bucket) # 使用快速排序 nums.extend(bucket) # 将排序好的桶依次放入到 nums 中
def check_sort(original): numbers = original[:] qs = QuickSort(numbers) output = qs.sort() print(output) if is_sorted(output): print("** SUCCESS! **") else: print("Uh oh - not in order.") if contain_same_ints(original, numbers): print("** Contain the same elements! **") else: print("Uh oh - something is missing.") print("---")
def do_search_user(self, item=None): """Search user profile.""" if not item: key = input("Provide the key to search item :") item = input(f"Provide {key} of user to be searched :") try: item = int(item) except: item = item else: key = 'id' item = int(item) self.do_all_users(self) sort_obj = QuickSort() result_set = sort_obj.resultset(self.user_data) sorted_data = sort_obj.sort(result_set, key=key) search_obj = BinarySearch() data = search_obj.search(sorted_data, item, key=key) print(data)
def quick_sort_in_threadings(self, t, nums): n = len(nums) ts = [] qs = [] for i in range(t): qs.append(QuickSort(nums[i * n // t:(i + 1) * n // t])) ts.append(Thread(target=lambda: qs[i].sort())) ts[i].start() for t in ts: t.join() return self.merge_n_sorted_arrays(list(map(lambda q: q.nums, qs)))
def main(): data = [] random.seed(time.time()) data = [_ for _ in range(0, 20)] random.shuffle(data) # data = [40] * 40 # data = [_ for _ in reversed(range(40))] print('source: {0}'.format(data)) start = time.time() qs = QuickSort(debug=True, save_fig=True) swap_times, fig_path = qs.sort(data) save_gif(fig_path, 'quick_sort.gif') stop = time.time() print('result: {0}\n'.format(data)) print('----------------------------------') print('swap times: {0}'.format(swap_times)) print('spend time: {0}s'.format(stop - start)) print('image path: {0}'.format(fig_path)) print('----------------------------------')
def main(): original = [325432, 989, 547510, 3, -93, 189019, 5042, 123, 597, 42, 7506, 184, 184, 2409, 45, 824, 4, -2650, 9, 662, 3928, -170, 45358, 395, 842, 7697, 110, 14, 99, 221] numbers = original[:] qs = QuickSort(numbers) output = qs.sort() if is_sorted(output): print("** SUCCESS! **") else: print("Uh oh - not in order.") if contain_same_ints(original, numbers): print("** Contain the same elements! **") else: print("Uh oh - something is missing.") print(output)
def selectKth(ar, left, right, k): #1 <= k <= right-left #idx = selectPivotIndex(ar,left,right); if left < right: pivot_index = QuickSort.subroutine(ar, left, right) #pay attention to this condition #the Kth means (k-1)th in a array(given that array start with 0) index = left + (k - 1) if pivot_index == index: return pivot_index if (index < pivot_index): return selectKth(ar, left, pivot_index, k) else: return selectKth(ar, pivot_index + 1, right, (index - pivot_index)) return
def selectKth(ar,left,right,k): #1 <= k <= right-left #idx = selectPivotIndex(ar,left,right); if left<right: pivot_index = QuickSort.subroutine(ar, left, right) #pay attention to this condition #the Kth means (k-1)th in a array(given that array start with 0) index = left+(k-1) if pivot_index == index: return pivot_index if (index < pivot_index): return selectKth(ar,left,pivot_index,k) else: return selectKth(ar,pivot_index+1,right,(index-pivot_index)) return
insert = np.zeros(shape=(100 * repetitions, 5)) array_index = 0 for k in range(0, repetitions): for n in range(100, 10100, 100): random_data = random.sample(range(n), n) qsort_data = random_data merge_data = random_data insert_data = random_data dqsort_data = random_data # Perform QuickSort on our randomly-generated data q_sorting = QuickSort() start = time.time() q_sorting.quick_sort(qsort_data, 0, len(qsort_data) - 1) end = time.time() elapsed = end - start qsort[array_index] = [ k, n, q_sorting._compares, q_sorting._shifts, elapsed ] # Perform MergeSort on our randomly-generated data m_sorting = MergeSort() start = time.time() result = m_sorting.mergesort_asc(merge_data)
from abstract_sort import AbstractSort from bubble_sort import BubbleSort from quick_sort import QuickSort from heap_sort import HeapSort from python_sort import PythonSort from sort_time_complexity import SortTimeComplexity if __name__ == '__main__': stc = SortTimeComplexity() stc.run_sorter_tests(BubbleSort()) stc.run_sorter_tests(QuickSort()) stc.run_sorter_tests(HeapSort()) stc.run_sorter_tests(PythonSort()) stc.display_plot()
def __init__(self): self.graph = CityGraph() self.quick_sort = QuickSort() self.merge_sort = MergeSort()
def test(self, args): QuickSort.sort(args) assert QuickSort.is_sorted(args) QuickSort.show(args)
def fn_quick_sort(input, output, start): q_sort = QuickSort() q_sort.quick_sort(0, len(input) - 1, input) assert input == output end = time.time()
import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[3]: import random import sys # ## Generate Data and Sort # In[24]: isort = InsertSort([]) msort = MergeSort([]) qsort = QuickSort([]) i_runtime = [] m_runtime = [] q_runtime = [] i_jmptime = [] m_jmptime = [] q_jmptime = [] i_cmprtime = [] m_cmprtime = [] q_cmprtime = [] # In[25]:
def test_quick_sort_duplicated_number(): actual = QuickSort(arr=[2, 5, 5, 3, 5], left=0, right=len([2, 5, 5, 3, 5]) - 1) expected = [2, 3, 5, 5, 5] assert actual == expected
def test_quick_sort_sortedd_reverse(): actual = QuickSort(arr=[12, 9, 7, 5, 2], left=0, right=len([12, 9, 7, 5, 2]) - 1) expected = [2, 5, 7, 9, 12] assert actual == expected
from sort import Sort from insert_sort import InsertSort from merge_sort import MergeSort from quick_sort import QuickSort import numpy as np import matplotlib.pyplot as plt import random import sys rdmlist = np.random.randint(100, size=10) asdlist = list(range(1, 901)) # print(rdmlist) #isort = InsertSort(rdmlist) #msort = MergeSort(rdmlist) qsort = QuickSort(asdlist) # isort.time(isort.insert_sort) qsort.time(qsort.quick_sort) print(qsort.run_time)
from quick_sort import QuickSort my_list = [4, 6, 44, 57, 1, 77, 32, 11, 33, 3, 4] qc = QuickSort(my_list) print(qc.partition()) qc.quick_sort() print(my_list)
from radix_sort import RadixSort from heap_sort import HeapSort from merge_sort import MergeSort from quick_sort import QuickSort from bubble_sort import BubbleSort from selection_sort import SelectionSort from insertion_sort import InsertionSort from time import time import random options = { 1: ("Bubble Sort", BubbleSort()), 2: ("Selection Sort", SelectionSort()), 3: ("Insertion Sort", InsertionSort()), 4: ("Quick Sort", QuickSort()), 5: ("Merge Sort", MergeSort()), 6: ("Radix Sort", RadixSort()), 7: ("Counting Sort", CountingSort()), 8: ("Heap Sort", HeapSort()) } print("Sorting Options: ") for i in options.keys(): print("Option {} : {}".format(i, options[i][0])) while True: option = int(input("Enter sorting option: ")) sort_alg = options[option][1] start = time() arr = [random.randint(-100000, 100000) for _ in range(10)] print(arr) sort_alg.sort(arr)
def test_quick_sort_negative(): actual = QuickSort(arr=[2, -4, 5, 3, 8], left=0, right=len([-4, 2, 3, 5, 8]) - 1) expected = [-4, 2, 3, 5, 8] assert actual == expected
from utils import algorithms.CArray from selection_sort import selection_sort from bubble_sort import bubble_sort from insertion_sort import insertion_sort from quick_sort import QuickSort list = algorithms.CArray(20) list.set_data() print('///// ARRAY TO ORDER /////') print(list.data_store) print('//////////////////////////') print('QuickSort') sortable_array = QuickSort(list.data_store) sortable_array.quick_sort(0, len(list.data_store) - 1) print(sortable_array.array) print('BubbleSort') print(bubble_sort(list.data_store)) print('SelectionSort') print(selection_sort(list.data_store)) print('InsertionSort') print(insertion_sort(list.data_store))
# repetition for different orders of array size for i in range(1,n): l = 10**i # order of array size arr = [int(random.random()*100) for j in range(l)] # create an array of random numbers with incremental order alist = [0]*len(arr) # initialize an empty array of same size times[i-1][0] = l # add the order as the first column in the matrix # a loop to go through all the sorting algorithms for g in range(1, 6): start = time.clock() # get a CPU clock tick if g == 1: temp = SelectionSort.sort(dup(alist, arr)) elif g == 2: temp = InsertionSort.sort(dup(alist, arr)) elif g == 3: temp = MergeSort.sort(dup(alist, arr)) elif g == 4: temp = QuickSort.sort(dup(alist, arr)) elif g == 5: temp = CountSort.sort(dup(alist, arr)) end = time.clock() - start # get a CPU clock tick and estimate algorithm r setin(i, end, g) endit = time.clock() - begin # estimate overal calculation time print ('Total time Elapsed:', endit, 'seconds.') # show the benchmark matrix for i in range(0, n-1): print (times[i])
def quick_sort(self, nums): instance = QuickSort(nums) instance.sort()
def test_quick_sort(self): sortedList = QuickSort.quick_sort(self.targetList) self.assertTrue(sortedList == self.checkList)
def quick_sort(array): start = timeit.default_timer() copied_array = copy.copy(array) QuickSort.sort(array=copied_array) end = timeit.default_timer() return format(end - start, '.5f')
def test_quick_sort(self): algo = SortingTestWrapper(QuickSort(), self.n, self.seed) self.assertListEqual(algo.integer_sort(), self.verification.integer_sort())
def test_quick_sort(): actual = QuickSort(arr=[2, 4, 5, 3, 8], left=0, right=len([2, 3, 4, 5, 8]) - 1) expected = [2, 3, 4, 5, 8] assert actual == expected