示例#1
0
 def test_quickSort(self):
     self.assertEqual(quickSort([8, 1, 2, 3, 4, 5, 6, 7]),
                      [1, 2, 3, 4, 5, 6, 7, 8])
     self.assertEqual(quickSort([10, 5, 90, 0, 10]), [0, 5, 10, 10, 90])
     self.assertEqual(quickSort([64, 34, 25, 22, 11, 90, 12]),
                      [11, 12, 22, 25, 34, 64, 90])
     self.assertEqual(quickSort([8, 90, 4, 1, 5, 5]), [1, 4, 5, 5, 8, 90])
     self.assertEqual(quickSort([1, 2, 3, 4, 5, 5]), [1, 2, 3, 4, 5, 5])
示例#2
0
def StartAlgorithm():
    global data
    if not data:
        return

    if algo_menu.get() == 'Quick Sort':
        quickSort(data, 0, len(data) - 1, drawData, speedscale.get())

    elif algo_menu.get() == "Bubble Sort":
        bubbleSort(data, drawData, speedscale.get())
示例#3
0
def calcularTiempoAlgoritmos(tiemposEjecucion, tamanio,archivo):
    tiempos=[]
    #Tiempo RadixSort
    arreglo = generarArreglo(tamanio)
    inicio = time()
    ordenadoRadix = radixSort(arreglo.copy(), 10)
    final = time()
    tiempos.append(final-inicio)

    #Tiempo QuickSort
    aux = arreglo.copy()
    inicio = time()
    quickSort(aux)
    final = time()
    tiempos.append(final-inicio)


    # Tiempo CountingSort
    aux2 = arreglo.copy()
    inicio = time()
    countingSort(aux2, tamanio)
    final = time()
    tiempos.append(final-inicio)


    #Tiempo CombSort
    aux3 = arreglo.copy()
    inicio = time()
    combsort(aux3)
    final = time()
    tiempos.append(final-inicio)
    

    #Tiempo ShellSort
    aux4 = arreglo.copy()
    inicio = time()
    shellSort(aux4)
    final = time()
    tiempos.append(final-inicio)
    

    #Tiempo InsertionSort
    aux5 = arreglo.copy()
    inicio = time()
    insertsort(aux5)
    final = time()
    tiempos.append(final-inicio)
    
    archivo.write("10")
    for element in tiempos:
        linea+=","+str(element)
    archivo.write("\n")
def find_duplicates(A):
    a = quickSort(A)
    for i in range(len(a) - 1):
        for j in range(i + 1, len(a)):
            if a[i] == a[j]:
                return True
    return False
def calcularTiempoAlgoritmos(arreglo, tamanio,archivo):
    tiempos=[]
    #Tiempo RadixSort
    arreglo = generarArreglo(arreglo,tamanio)
    inicio = time()
    ordenadoRadix = radixSort(arreglo.copy(), 10)
    final = time()
    tiempos.append(final-inicio)

    #Tiempo QuickSort
    aux = arreglo.copy()
    inicio = time()
    quickSort(aux)
    final = time()
    tiempos.append(final-inicio)


    # Tiempo bubbleSort
    aux2 = arreglo.copy()
    inicio = time()
    bubbleSort(aux2)
    final = time()
    tiempos.append(final-inicio)


    #Tiempo shellSort
    aux3 = arreglo.copy()
    inicio = time()
    shellSort(aux3)
    final = time()
    tiempos.append(final-inicio)
    

    #Tiempo heapsort
    aux4 = arreglo.copy()
    inicio = time()
    heapsort(aux4)
    final = time()
    tiempos.append(final-inicio)
    
    
    archivo.write(str(tamanio))
    for element in tiempos:
        linea+=","+str(element*1000) #para que quede en milisegundos
    archivo.write("\n")
示例#6
0
def count_votes_2(A):
    a = quickSort(A)
    counter = max = 0
    id = maxid = 0
    for i in range(len(A)):
        if A[i] == id:
            counter += 1
        else:
            counter = 1
            id = A[i]
        if counter > max:
            maxid = id
            max = counter
    return maxid
 def test_quickSort(self):
     a = [10, 5, -4, 25]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [-4, 5, 10, 25])
     a = [22, 4, 1, 4]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [1, 4, 4, 22])
     a = [100, -100, 1, 0]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [-100, 0, 1, 100])
     a = [0, 4, 0, -5, 1, 4]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [-5, 0, 0, 1, 4, 4])
     a = [0, 0, 0]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [0, 0, 0])
     a = [12314, 235987, -54621]
     self.assertEqual(quickSort(a, 0, len(a) - 1), [-54621, 12314, 235987])
from IsSorted import isSorted

from QuickSort import quickSort

# Test verification function

assert(isSorted([5,1,2,4,9,8,7,1,9]) == False)

assert(isSorted([1,1,2,4,5,7,8,9,9]) == True)

# Quick-sort, base case: Empty sequence

sequence = []

quickSort(sequence)

assert(isSorted(sequence))

# Quick-sort, base case: 1-element sequence

sequence = [7]

quickSort(sequence)

assert(isSorted(sequence))

# Quick-sort, simple recursive case: 3-element sequence

sequence = [8,13,5]
示例#9
0
from QuickSort import quickSort
from ShellSort import startShellSort

list = [16, 9, 15, 90, 4]
# list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
numbersList = list.copy()
numbersList2 = list.copy()

h1 = 2
h2 = 5


startShellSort(numbersList, h1, h2)

quickSort(numbersList2, 0, len(numbersList2)-1)

print(numbersList2)
示例#10
0
from QuickSort import quickSort
import numpy as np

size = raw_input("Input random array size: ")
boundary = raw_input("Input upper boundary of the number in random array: ")

list_1 = np.random.randint(int(boundary), size=int(size)).tolist()
list_2 = np.random.randint(int(boundary), size=int(size)).tolist()

print("initial array:\n" + str(list_1))
quickSort(list_1, 0, len(list_1) - 1, 'first')
print("result array:\n" + str(list_1))
print("initial array:\n" + str(list_2))
quickSort(list_2, 0, len(list_2) - 1, 'last')
print("result array:\n" + str(list_2))
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!!!")
        for k in range(0, n-1):
            if data[k] > data[k+1]:
                print("error!")
                break
示例#12
0
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"
示例#13
0
from Bubble import bubble
import random
from Merge import mergeSort
from QuickSort import quickSort
from Selection import selection
import matplotlib.pyplot as plt

x = input("Enter what sorting you want to visualize: ")
n = int(input("Enter size of array: "))
A = random.sample(range(1, n + 1), n)

if x == 'b':
    bubble(A)
elif x == 'm':
    mergeSort(A, 0, n - 1)
elif x == 'q':
    quickSort(A, 0, n - 1)
elif x == 's':
    selection(A)

plt.bar(list(range(0, len(A))), A)
plt.pause(0.1)
plt.close()
def find_missing_element(A):
    a = quickSort(A)
    for i in range(len(a) - 1):
        if not (A[i + 1] - A[i] == 1):
            return A[i] + 1
    return -1
    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)
    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 Quick Sort is:", avgTime)

#Perform modified quick sort and take average time by running it thrice
avgTimeArray = []
for x in range(3):
    input4 = copy.deepcopy(content)
    start = time.time()
    result = quicksort_median(input4, 0, len(input4) - 1)
示例#16
0
from QuickSort import quickSort, partition, quickSortE, partitionE
import random

a = []
b = []
N = 16
for i in range(0, N):
	a.append(int(random.uniform(0, 8*N)))
	b.append(int(random.uniform(0, 1*N)))

def printList(a):
	for i in a:
		print(i, end = ' ')
	print()

printList(a)
quickSort(a, 0, N-1)
printList(a)

#printList(b)
#quickSortE(b, 0, N-1)
#printList(b)
示例#17
0
import unittest
from QuickSort import quickSort
import numpy as np

class TestHeapSort(unittest.TestCase)

    def test_heapsort(self)
        arr = [5, 4, 3, 1, 2]
	    sortedArray = quickSort(arr)
	    result = np.arrayEqual([1, 2, 3, 4, 5], sortedArray)
		self.assertTrue(result)


if __name__ == '__main__'
    unittest.main()
示例#18
0
def sort(l):
    limit = 30
    if len(l) < 30:
        insertionSort(l)
    else:
        quickSort(l)