def test_time_to_sort_arr(key, f): t1, t2, t3 = 0, 0, 0 for i in range(1000, 11000, 1000): f.write("{0} |".format(i)) for j in range(TIMES): arr = sort.generateArr(i, key) start = process_time() sort.bubbleSort(arr) end = process_time() t1 += (end - start) arr = sort.generateArr(i, key) start = process_time() sort.insertSort(arr) end = process_time() t2 += (end - start) arr = sort.generateArr(i, key) start = process_time() sort.gnomeSort(arr) end = process_time() t3 += (end - start) f.write(" {0:<.15f} | {1:<.15f} | {2:<.15f} |\n".format( t1 / TIMES, t2 / TIMES, t3 / TIMES))
def main(): print( bubbleSort([ 4, 4, 4, 4, 4, 4, 5, 4, 5, 5, 46, 4, 564, 5, 45, 45, 1, 546, 5, -8, -9, -456545, -4564, -1 ])) print(bubbleSort([4, 4, 4, 4, 4, 4])) print(bubbleSort([]))
def sortList(self, myList): if (self.sortingAlg == 'Bubble Sort'): bubbleSort(myList, delay=self.sleepTime) elif (self.sortingAlg == 'Merge Sort'): mergeSort(myList, delay=self.sleepTime) elif (self.sortingAlg == 'Quick Sort'): quickSort(myList, delay=self.sleepTime) self.buttons[1].setText('Start') self.sorting = False
def main(): list1 = [] num = input("\t欢迎使用排序演示程序\n" + "请输入你想要产生的随机数个数:") for i in range(int(num)): list1.append(int(random.random() * 100)) length = len(list1) print("\n=========排序方法选择==========\n" + "1.插入排序 2.折半插入排序\n" + "3.希尔排序 4.冒泡排序 \n" + "5.快速排序 6.直接选择排序\n" + "7.堆排序 8.基数排序 \n") fun = input("请输入你想要使用的排序函数:") if int(fun) < 1 or int(fun) > 8: print("没有这个排序函数,请重新选择") time.sleep(3) os.system("clear") main() elif fun == '1': st.insertSort(list1, length) elif fun == '2': st.binaryInsertSort(list1, length) elif fun == '3': st.shellSort(list1, length) elif fun == '4': st.bubbleSort(list1, length) elif fun == '5': st.quickSort(list1, 0, length - 1) elif fun == '6': st.directSelectSort(list1, length) elif fun == '7': st.heapSort(list1, length) elif fun == '8': st.radixSort(list1) print("\n---------------------------分割线--------------------------\n") main()
def bubbleSortTime(): SETUP_CODE = ''' import sort import random testList = [] for i in range(50000): testList.append(random.randint(0,1000))''' TEST_CODE = ''' sort.bubbleSort(testList)''' times = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE, repeat=1, number=1) print('bubbleSortTime: {}'.format(min(times)))
print('2 - Scan Array') print('3 - Selection Sort') print('4 - Insertion Sort') print('5 - Bubble Sort') print('6 - Shell Sort') print('7 - Quick Sort') print('0 - Exit') print('==================') def scanArray(): for i in range(length): array[i] = int(input('Enter the value [' + str(i) + ']: ')) return array op = 1 while op: printMenu() op = int(input('Choose an option: ')) if op == 0: print('You chose to leave') elif op == 1: print(array) elif op == 2: print(scanArray()) elif op == 3: print(sort.selectionSort(array)) elif op == 4: print(sort.insertionSort(array)) elif op == 5: print(sort.bubbleSort(array)) elif op == 6: print(sort.shellSort(array)) elif op == 7: print(sort.quickSort(array, 0, length - 1)) else: print('Please choose a valid option')
def bubbleSortTest(mode): # ------------------------------------------------------------------------------------------ X = [ ] # Eje de Abscisas para la recta de regresion para predecir los tiempos Y = [ ] # Eje de Ordenadas para la recta de regresion para predecir los tiempos # ------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------ # Bubble Sort # ------------------------------------------------------------------------------------------ print('Bubble Sort') for i in [5, 10, 50, 100, 500, 1000, 5000, 10000]: start_time = time.time() A = arrayGen.genArray(i, mode) (comp, asig, objc, malloc) = sort.bubbleSort(A) end_time = time.time() - start_time compUT = comp << 1 # comp << 1 = comp * 2 (Bitwise) asigUT = asig << 3 # asig << 3 = comp * 8 (Bitwise) objcUT = objc * 200 mallocUT = 50 + (malloc * 10) totalUT = compUT + asigUT + objcUT + mallocUT X.append(float(totalUT)) Y.append(float(end_time)) print(f'\tComparaciones:\t\t\t{comp} = {compUT}ut') print(f'\tAsignaciones:\t\t\t{asig} = {asigUT}ut') print(f'\tInstancias (objetos):\t\t{objc} = {objcUT}ut') print(f'\tEspacio de memoria alojado:\t{malloc} = {mallocUT}ut') print(f'\tTotal:\t\t\t\t\t\t{totalUT}ut') # Total print('--- %s seconds ---\n' % (end_time)) # ------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------ # Prediccion de tiempos mediante recta de regresion lienal # ------------------------------------------------------------------------------------------ X2 = linearAlgebra.powScaleVector(X, 2) XY = linearAlgebra.vecProd(X, Y) sumX = sum(X) sumY = sum(Y) sumX2 = sum(X2) sumXY = sum(XY) n = len(X) M = [[n, sumX], [sumX, sumX2]] B = [sumY, sumXY] V = linearAlgebra.gauss(M, B) w0, w1 = V[0], V[1] # ------------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------ print( '100000, 1000000, ... son muy costosos en la ejecución de este algoritmo' ) print( "Para ello mediante el metodo de minimos cuadrados obtuvimos 3 parametros" ) print( "Estos 3 parametros dan forma a la ecuacion lineal de tiempos del tipo:" ) print("w0 + w1 * ut + w2 * ut^2\n") for n in [100000, 1000000, 10000000, 100000000]: comp = n**2 + 2 * n - 2 compUT = comp << 1 asig = n**2 + 3 * n - 2 asigUT = asig << 3 objc = 0 objcUT = objc * 200 malloc = 0 mallocUT = 50 + (malloc * 10) totalUT = compUT + asigUT + objcUT + mallocUT print(f'n = {n} =>') print(f'\tComparaciones:\t\t\t{comp} = {compUT}ut') print(f'\tAsignaciones:\t\t\t{asig} = {asigUT}ut') print(f'\tInstancias (objetos):\t\t{objc} = {objcUT}ut') print(f'\tEspacio de memoria alojado:\t{malloc} = {mallocUT}ut') print(f'\tTotal:\t\t\t\t\t\t{totalUT}ut') # Total print(f'--- {w0 + w1 * totalUT} seconds ---\n') print("Gracias a ello pudimos predecir todas las ultimas medidas") return (w0, w1)
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:randomList.py # @Author: Michael.liu # @Date:2020/7/22 13:12 # @Desc: this code is .... import random from sort.bubbleSort import * from sort.helper import * from sort.selectionSort import selectionSort import timeit if __name__ == "__main__": iList = randomList(10) print(iList) print(bubbleSort(iList)) print( timeit.timeit("bubbleSort(iList)", "from __main__ import bubbleSort,iList", number=100)) print("=========selection=========") print(selectionSort(iList)) print( timeit.timeit("selectionSort(iList)", "from __main__ import selectionSort,iList", number=100))
from sort import bubbleSort arr = [9, 3, 5, 1, 2, 4, 5, 7, 8, 8, 1] bubbleSort(arr) print(arr)
#iterativeMergeSortTime() #Sys code for the command line import sys if len(sys.argv) < 2: print() elif sys.argv[1] == "BubbleSort": if len(sys.argv) > 3: if sys.argv[3] == "PRINT": testList = [] for i in range(int(sys.argv[2])): testList.append(random.randint(0, 10000)) print(testList, "\n") sort.bubbleSort(testList) print(testList) else: testList = [] for i in range(int(sys.argv[2])): testList.append(random.randint(0, 10000)) sort.bubbleSort(testList) print("LIST SORTED") elif sys.argv[1] == "InsertionSort": if len(sys.argv) > 3: if sys.argv[3] == "PRINT": testList = [] for i in range(int(sys.argv[2])): testList.append(random.randint(0, 10000)) print(testList, "\n")
import sort import random lyst = [1, 3, 2, 4, 7, 6, 5] print(lyst) sort.selectionSort(lyst) print(lyst) lyst = [1, 3, 2, 4, 7, 6, 5] print(lyst) sort.bubbleSort(lyst) print(lyst) lyst = [1, 3, 2, 4, 7, 6, 5] print(lyst) sort.insertionSort(lyst) print(lyst) lyst = [] for count in range(1000): lyst.append(random.randint(1, 200)) print(lyst) sort.quicksort(lyst) print(lyst)
import matplotlib.pyplot as plt from tqdm import tqdm import numpy as np if __name__ == '__main__': print('also look here: ', __name__) MIN = 0 MAX = 1000 bubble_sort_mean = [] merge_sort_mean = [] bubble_sort_std_dev = [] merge_sort_std_dev = [] arr_sizes = [] for i in tqdm(range(5, 1000, 100)): sample = random.choices(range(MIN, MAX), k=i) thing = bubbleSort(sample, timeme=True) thing = mergeSort(sample, timeme=True) experiment = Timer.records['sorting_experiment'] arr_sizes.append(int(i)) bubble_sort_mean.append(experiment['bubbleSort'][-1].aggregate['mean']) bubble_sort_std_dev.append( experiment['bubbleSort'][-1].aggregate['std_dev']) merge_sort_mean.append(experiment['mergeSort'][-1].aggregate['mean']) merge_sort_std_dev.append( experiment['mergeSort'][-1].aggregate['std_dev']) bubble_sort_mean = np.array(bubble_sort_mean) bubble_sort_std_dev = np.array(bubble_sort_std_dev) merge_sort_mean = np.array(merge_sort_mean) merge_sort_std_dev = np.array(merge_sort_std_dev) plt.plot(arr_sizes,
import random, time from sort import bubbleSort mylist = [54, 26, 93, 17, 77, 31, 44, 55, 20] bubbleSort(mylist) print(mylist)
exit() ################################################### ################ Sorting the array ################ print('\nSorting in progress...') sorts, times, comparisons, accesses = [], [], [], [] for i in range(tries): startTime = time() if algorithm == '1': sorted_array, comparison, access = sort.someSort(unsorted_array) elif algorithm == '2': sorted_array, comparison, access = sort.insertionSort(unsorted_array) elif algorithm == '3': sorted_array, comparison, access = sort.selectionSort(unsorted_array) elif algorithm == '4': sorted_array, comparison, access = sort.bubbleSort(unsorted_array) elif algorithm == '5': sorted_array, comparison, access = sort.mergeSort(unsorted_array) elif algorithm == '6': sorted_array, comparison, access = sort.bogoSort(unsorted_array) times.append(time() - startTime) sorts.append(sorted(unsorted_array) == sorted_array) comparisons.append(comparison) accesses.append(access) ################################################### ################ Analyze test data ################ print('Sorting finished!\n') print('Length of array: %d' % len(unsorted_array)) print('Sorted: %d/%d (%d%%)' % (sorts.count(True), tries, sorts.count(True) / tries * 100))