コード例 #1
0
def StartAlgorithm():
    global data

    scale = speedScale.get()
    if not data: return

    if algMenu.get() == 'Quick Sort':
        quick_sort(
            data,
            0,
            len(data) - 1,
            drawData,
            scale,
        )

    elif algMenu.get() == 'Bubble Sort':
        bubbleSort(data, drawData, scale)
    elif algMenu.get() == 'Selection Sort':
        selectionSort(data, drawData, scale)
    elif algMenu.get() == 'Merge Sort':
        mergeSort(data, drawData, scale)
    elif algMenu.get() == 'Insertion Sort':
        insertionSort(data, drawData, scale)

    drawData(data, ['green' for x in range(len(data))])
コード例 #2
0
def sampleMedianSelect(list, left, right, m):
    if m >= len(list[left:right + 1]):
        #print("m>len(list)->decreasing m")
        m = len(list[left:right + 1])
    S = random.sample(list[left:right + 1], m)
    if m <= 20:
        selectionSort(S)
    else:
        mergeSort(S)
    return S[ceil(len(S) / 2)]
コード例 #3
0
ファイル: Main.py プロジェクト: Yurchezz/LoveStory
def main():
    arr = [1, 8, 3, 5, 4, 3]
    P = 100
    mergeSort(arr)
    print(arr)

    if findThreeNumbers(arr, P) is None:
        print("Not this time, Ilona")
    else:
        print(findThreeNumbers(arr, P))
コード例 #4
0
def Search2Elements(S,x):
    for i in range(0,len(S)-1):
        key = x-S[i]
        mergeSort(S, 0 , len(S)-1)
        loc = IterativeBinarySearch(S,key,i+1,len(S)-1)
        if(S[loc] == key):
            print '2 Elements exist whose sum is equal to {0}'.format(x)
            return 1

    print '2 Elements do not exist that sum to {0}'.format(x)
    return 0
コード例 #5
0
ファイル: SummaryStats.py プロジェクト: rds6y9/Course_Work
def getPercentile(num_list, percentile):
    if percentile < 0 or percentile > 1:
        return "Incorrect percentile provided"

    sorted_list = mergeSort(num_list)
    percentile_index = math.floor(len(sorted_list) * percentile)

    return sorted_list[percentile_index]
コード例 #6
0
ファイル: SummaryStats.py プロジェクト: rds6y9/Course_Work
def getMedian(num_list):
    sorted_list = mergeSort(num_list)

    # Median is the middle value
    if len(sorted_list) % 2 == 0:  # is even length
        print("Element 1: " + str(sorted_list[len(sorted_list) // 2]))
        print("Element 2: " + str(sorted_list[(len(sorted_list) // 2) + 1]))
        return (sorted_list[len(sorted_list) // 2] +
                sorted_list[(len(sorted_list) // 2) + 1]) / 2
    # else is odd length
    return sorted_list[len(sorted_list) // 2]
コード例 #7
0
    def test_MergeSort(self):
        sorted_data_1 = mergeSort(self.data_1)

        self.assertEqual(sorted_data_1[0], 1)
        self.assertEqual(sorted_data_1[1], 2)
        self.assertEqual(sorted_data_1[2], 3)
        self.assertEqual(sorted_data_1[3], 4)
        self.assertEqual(sorted_data_1[4], 5)
        self.assertEqual(sorted_data_1[5], 6)
        self.assertEqual(sorted_data_1[6], 7)
        self.assertEqual(sorted_data_1[7], 8)
        self.assertEqual(sorted_data_1[8], 9)
        self.assertEqual(sorted_data_1[9], 10)
コード例 #8
0
 def test_mergeSort(self):
     a = [10, 5, -4, 25]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [-4, 5, 10, 25])
     a = [22, 4, 1, 4]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [1, 4, 4, 22])
     a = [100, -100, 1, 0]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [-100, 0, 1, 100])
     a = [0, 4, 0, -5, 1, 4]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [-5, 0, 0, 1, 4, 4])
     a = [0, 0, 0]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [0, 0, 0])
     a = [12314, 235987, -54621]
     self.assertEqual(mergeSort(a, 0, len(a) - 1), [-54621, 12314, 235987])
コード例 #9
0
        while inf <= right and l[inf] <= l[indice]:
            inf += 1
        sup -= 1
        while l[sup] > l[indice]:
            sup -= 1
        if inf < sup:
            l[inf], l[sup] = l[sup], l[inf]
        else:
            break
    l[indice], l[sup] = l[sup], l[indice]
    print("- " * left + str(l[left:right + 1]) + " -" * (len(l) - right - 1))
    return sup

# Breve main per il test dell'algoritmo

if __name__ == "__main__":
    #A = []
    A = [30, 30, 30, 30, 30]
    A=[]
    dim=1000
    random.seed(2)
    """for i in range(0,dim):
        A.append(random.randint(0,dim+1000))"""
    B=A
    QuickSort(A,50)
    mergeSort(B)
    for i in range(0,len(A)-1):
        if A[i]!=B[i]:
            print("NOT EQUAL")
            break
    print("EQUAL")
コード例 #10
0
sort_fun = input("please input sorting method (merge/quick/heap/insertion):")
n = int(input('please input length of data :'))
nk = str(n//1000)
dict_n = {10000: "B", 20000: "C", 40000: "D"}

for i in range(1, 13):
    pwd = './HW1/'+nk+'k/'+nk+'k'+"{:02d}".format(i)+'.txt'
    print('Reading '+nk+"k{:02d}".format(i)+'.txt'+'....', end='')
    with open(pwd, 'r') as fn:
        data = []
        for line in fn:
            data.append(int(line))
        if sort_fun == 'merge':
            start = time.time()
            mergeSort(data)
            total = time.time() - start
        elif sort_fun == 'quick':
            start = time.time()
            quickSort(data, 0, len(data)-1)
            total = time.time() - start
        elif sort_fun == 'heap':
            start = time.time()
            heapSort(data)
            total = time.time() - start
        elif sort_fun == 'insertion':
            start = time.time()
            insertionSort(data)
            total = time.time() - start
        else:
            print("please input correct method!!!")
コード例 #11
0
ファイル: menu.py プロジェクト: cfloresm/AlgorithmsPython
def options():
	#Ciclo while para desplegar el menu hasta que se precione la tecla 0
	count = 1
	while (count != 0):

		#Menu de opciones
		print "\n"
		print "Que algoritmo quieres implementar ?"
		print "0.- Salir del Menu"
		print "1.- MergeSort"
		print "2.- QuickSort"
		print "3.- Insertion Sort"
		print "4.- Fibonacci Iterativo"
		print "5.- Fibonacci Recursivo"
		print "6.- Fibonacci Tramposo"
		print "7.- Fibonacci con Matrices"
		print "\n"
		
		#Se lee el entero para saber que opcion se va a ejecutar
		n = int(sys.stdin.readline())
		
		#Validacion, que el numero tecleado le corresponda una opcion	
		if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5 or n == 6 or n == 7:
			
			#Funcionalidad del menu, se utiliza la sentencia de control if para ejecutar el algoritmo seleccionado en el menu de opciones
			if n == 0:
				count = n
			elif n == 1: 
				print "******************Merge Sort*********************\n"
		     		print mergeSort( readFileNumbers() )
				print "***************************************************************************************"
			elif n == 2:
				print "******************Quick Sort*********************\n"
				print quickSort( readFileNumbers() )
				print "***************************************************************************************"
			elif n == 3:
				print "******************Insertion Sort*********************\n"
		     		print insertSort( readFileNumbers() )
				print "***************************************************************************************"
			elif n == 4:
				print "******************Fibonacci Iterativo*********************\n"
				print "\nEl fibonacci de que numero quieres obtener"
		  		number = int(sys.stdin.readline())
				print "El fibonacci en la posicion "+ str(number) + " es: " + str(fibIte(number)) +"\n\n"
				for i in range (0, number+1):
					print ("Fibonacci iterativo en la posicion: "+str(i)+"--> "+str(fibIte(i)))
				print "*******************************************************************"	
			elif n == 5:
				print "******************Fibonacci Recursivo*********************\n"
				print "\nEl fibonacci de que numero quieres obtener"
		  		number = int(sys.stdin.readline())
				print "El fibonacci en la posicion "+ str(number) + " es: " + str(fibRec(number)) +"\n\n"
				for i in range (0, number+1):
					print ("Fibonacci recursivo en la posicion: "+str(i)+"--> "+str(fibRec(i)))
				print "*******************************************************************"	
			elif n == 6:
				print "******************Fibonacci Trampozo*********************\n"
				print "\nEl fibonacci de que numero quieres obtener"
		  		number = int(sys.stdin.readline())
				print "El fibonacci en la posicion "+ str(number) + " es: " + str(fibTramp(number)) +"\n\n"
				for i in range (0, number+1):
					print ("Fibonacci iterativo en la posicion: "+str(i)+"--> "+str(fibTramp(i)))
				print "*******************************************************************"	
			elif n == 7:
				print "******************Fibonacci Matriz*********************\n"
		  		print "\nEl fibonacci de que numero quieres obtener"
		  		number = int(sys.stdin.readline())
		  		print "El fibonacci en la posicion "+ str(number) + " es: " + str(fibMat(number)) +"\n\n"
				for i in range(0, number+1):
					print ("Fibonacci con matrices: "+str(i)+"--> "+str(fibMat(i)))
				print "*******************************************************************"
		else:
			print "********* Has tecleado un numero al cual no le corresponde ninguna opcion ******************"				
	print "Bye"
コード例 #12
0
 def test_already_sorted(self):
     input = [0, 1, 2, 3, 4, 5]
     self.assertEqual(mergeSort(input), sorted(input),
                      "Should be [0,1,2,3,4,5]")
コード例 #13
0
            end = time()
            temp = end - start
            print("Sample sorted with inserctionSort time -->", temp)

            A = B
            start = time()
            test9.QuickSort(A, m)  # Sample ordered with bubbleSort
            end = time()
            temp = end - start
            print("Sample sorted with bubbleSort time -->", temp)

            # OTHER SORTING ALGHORITMS

            A = B
            start = time()
            mergeSort(A)  # mergeSort
            end = time()
            temp = end - start
            print("Array sorted with mergeSort time-->", temp)

            A = B
            start = time()
            heapSort(A)  # heapSort
            end = time()
            temp = end - start
            print("Array sorted with heapSort time-->", temp)

            A = B
            start = time()
            quickSort(A, False)  # non-deterministic quickSort
            end = time()
コード例 #14
0
 def test_unsorted_array(self):
     input = [1, 5, 63, 3, 54, 1]
     self.assertEqual(mergeSort(input), sorted(input),
                      "Should be [1, 1, 3, 5, 54, 63]")
コード例 #15
0
 def test_backwards_array(self):
     input = [5, 4, 3, 2, 1]
     self.assertEqual(mergeSort(input), sorted(input),
                      "Should be [1, 2, 3, 4, 5]")
コード例 #16
0
ファイル: Main.py プロジェクト: tudorgergely/Labs
def mergeSortNames():
    print mergeSort(nameList, compareNames)
コード例 #17
0
ファイル: Main.py プロジェクト: VladutZzZ/Labs
def mergeSortInts():
    print mergeSort(intList, compareInts)
コード例 #18
0
    result = insertionSort(input1, 0, len(content) - 1)
    end = time.time()
    timeElapsed = end - start
    avgTimeArray.append(timeElapsed)
temp = 0.0
for x in range(3):
    temp += avgTimeArray[x]
avgTime = temp / 3
print("Execution time for Insertion Sort is:", avgTime)

#Perform merge sort and take average time by running it thrice
avgTimeArray = []
for x in range(3):
    input2 = copy.deepcopy(content)
    start = time.time()
    result = mergeSort(input2)
    end = time.time()
    timeElapsed = end - start
    avgTimeArray.append(timeElapsed)
temp = 0.0
for x in range(3):
    temp += avgTimeArray[x]
avgTime = temp / 3
print("Execution time for Merge Sort is:", avgTime)

#Perform in-place quick sort and take average time by running it thrice
avgTimeArray = []
for x in range(3):
    input3 = copy.deepcopy(content)
    start = time.time()
    result = quickSort(input3, 0, len(input3) - 1)
コード例 #19
0
ファイル: Main.py プロジェクト: VladutZzZ/Labs
def mergeSortNames():
    print mergeSort(nameList, compareNames)
コード例 #20
0
import random
from time import time
from MergeSort import mergeSort

a = []
b = mergeSort()

for i in range(0, 100):
    a.append(random.randint(0, 1000))

print(a)

inicio = time()
c = b.MergeSort(a)
t_final = time() - inicio
print(c)
print(t_final)
コード例 #21
0
 def test_empty_array(self):
     input = []
     self.assertEqual(mergeSort(input), sorted(input), "Should be []")
コード例 #22
0
ファイル: Main.py プロジェクト: tudorgergely/Labs
def mergeSortInts():
    print mergeSort(intList, compareInts)