Example #1
0
def print_current_prize_money_ranking(players, return_value=False):

    leaderboard_in_list = list()

    header = '''============================
Current Prize Money Rankings
============================'''

    if not return_value:
        print(header)

    leaderboard_in_list.append(header)

    for player in players:
        player.compare_tournament_money = True
    QuickSort.sort(players)
    for player in players:
        player.compare_tournament_money = False

    for player in players:
        ranking_string = " Name: {0} Prize Money: {1}".format(
            player.name, player.tournament_money)
        leaderboard_in_list.append(ranking_string)
        if not return_value:
            print(" Name: {0} Prize Money: {1}".format(
                player.name, player.tournament_money))

    print
    if return_value:
        return leaderboard_in_list
Example #2
0
def r_median_search(numbers):
    subset = []
    n = len(numbers)
    pow = math.pow(n, float(3)/4)

    n_subset = int(math.ceil(pow))
    for i in range(n_subset):
        rn = rd.randint(0, len(numbers) - 1)
        subset.append(numbers[rn])

    subset = QuickSort.quicksort(subset)
    d = subset[int(math.floor(0.5 * pow - math.sqrt(n) - 1))]
    u = subset[int(math.floor(0.5 * pow + math.sqrt(n) - 1))]

    c = []
    lu = 0
    ld = 0
    for i in range(n):
        num = numbers[i]
        if num < d:
            ld += 1
        elif num > u:
            lu += 1
        else:
            c.append(num)

    success = False
    median = None
    if not(ld > n/2 or lu > n/2):
        if len(c) < 4 * pow:
            c = QuickSort.quicksort(c)
            median = c[int(math.ceil(n/float(2))) - ld - 1]
            success = True

    return success, median
Example #3
0
def run_test(fp):
    '''
    :param fp: file pointer to read in values
    :return: number of right and the length of the linked list

    creates linked lists and runs merge sort, then checks for correct result
    '''
    queue = stu_lq.LinkedQueue()
    count, answer = AddValues(queue, fp)
    stu_qs.quick_sort(queue)

    return check(answer, queue)
Example #4
0
    def determine_first_16(players):
        for player in players:
            player.compare_overall_points = True
            player.ranking_points = float(player.ranking_points)

        QuickSort.sort(players)

        for player in players:
            player.compare_overall_points = False

        for i, player in enumerate(players):
            if i < (len(players) / 2):
                player.in_first_16 = True
def RANDOM_PARTITION(A, p, r):
    # i = random.choice(A)
    # A[A.index(i)], A[r] = A[r], A[A.index(i)]
    i = random.choice(range(p, r + 1))
    A[i], A[r] = A[r], A[i]
    print "i is", i, "A is", A
    return QuickSort.PARTITION(A, p, r)
def calculate(numbers):

    numbers1 = list(numbers)
    start = time.time()
    median_quick_sort = QuickSort.quick_sort_median(numbers1)
    end = time.time()

    quick_sort_elapsed = end - start

    numbers2 = list(numbers)
    start = time.time()
    success, median_r = RMedian.r_median_search(numbers2)
    end = time.time()

    r_median_elapsed = end - start

    numbers3 = list(numbers)
    start = time.time()
    median_quick_select = QuickSelect.quick_select(numbers3, math.ceil(len(numbers3)/float(2)), 0)
    end = time.time()

    quick_select_elapsed = end - start

    if median_r != median_quick_sort:
        print("R Median Fail")
    # print ("Quick sort:" + str(median_quick_sort) + ", R median:" + str(median_r) + ", Quick Select Median:" + str(median_quick_select) )
    # print ("Quick sort time:" + str(quick_sort_elapsed) + ", R median time:" + str(r_median_elapsed) + ", Quick Select median time:" + str(quick_select_elapsed))
    # print ("")
    return  quick_sort_elapsed, r_median_elapsed, quick_select_elapsed, success
Example #7
0
def medicao_tempo(lista_de_entradas):
    times = []
    for entrada in lista_de_entradas:
        print("\n\n", len(entrada), "Entradas \n\n")
        sorters = [
            BubbleSortPlus(entrada[:]),
            BubbleSort(entrada[:]),
            QuickSortPF(entrada[:]),
            QuickSort(entrada[:]),
            HeapSort(entrada[:]),
            InsertionSort(entrada[:]),
            MergeSort(entrada[:]),
            SelectionSort(entrada[:]),
            ShellSort(entrada[:])
        ]

        #MEDINDO TEMPO DE ORDENAÇÃO
        for sorter in sorters:
            start = time.time()
            sorter.sort()
            end = time.time()

            tempo = end - start
            times.append([sorter.nome, len(entrada), tempo])

            print("TEMPO", sorter.nome, len(entrada), "ENTRADAS:", tempo)

    return times
Example #8
0
def main():
    base = input('Base: ').strip().capitalize()

    if base == 'Ordenada':
        CriandoDB.CreateDBOrdenada()  #Cria o data base
        DataBase = shelve.open('DBOrdenada')

    elif base == 'Inversa':
        CriandoDB.CreateDBInversa()  #Cria o data base
        DataBase = shelve.open('DBInversa')

    elif base == 'Aleatoria':
        CriandoDB.CreateDBAleatoria()  #Cria o data base
        DataBase = shelve.open('DBAleatoria')

    valores_comp_trocas_b = Conta_CT(DataBase, BubbleSort.bubblesort_regitros)
    Escreve('bubble', base, valores_comp_trocas_b)
    tempo = BubbleSort.Calcula_Tempo_Bubble(DataBase)
    Escreve('bubble', base, tempo, "tempo")

    valores_comp_trocas_i = Conta_CT(DataBase,
                                     InsetionSort.insertionsort_registros)
    Escreve('insertion', base, valores_comp_trocas_i)
    tempo = InsetionSort.Calcula_Tempo_insertion(DataBase)
    Escreve('insertion', base, tempo, "tempo")

    valores_comp_trocas_q = Conta_CT(DataBase, QuickSort.quickSort_registros)
    Escreve('quick', base, valores_comp_trocas_q)
    tempo = QuickSort.Calcula_Tempo_Quick(DataBase)
    Escreve('quick', base, tempo, "tempo")

    DataBase.close()
    return None
 def __init__(self, *args, **kwargs):
     super(Test, self).__init__(*args, **kwargs)
     #create a test list:
     x = []
     for i in range(300):
         x.append(random.randint(-100, 100))
     self.sorter = QuickSort.QuickSort(x, verbose=False)
Example #10
0
def test_mini_sort2():
    qs = QuickSort.Array([5, 3, 4, 2, 1])
    qs.PARTITION(0, 4)
    assert qs.A == [1, 3, 4, 2, 5]
    qs.PARTITION(1, 3)
    assert qs.A == [1, 2, 4, 3, 5]
    qs.PARTITION(2, 3)
    assert qs.A == [1, 2, 3, 4, 5]
Example #11
0
 def findMedian(self, arr):
     QuickSort().quickSort(arr, 0, len(arr) - 1)
     if (len(arr) % 2 == 0):
         median = (arr[int(len(arr) / 2)] + arr[int(
             (len(arr) - 1) / 2)]) / 2
     else:
         median = arr[int(len(arr / 2))]
     print(median)
Example #12
0
def test_mini_sort1():
    qs = QuickSort.Array([5, 4, 3, 2, 1])
    qs.PARTITION(0, 4)
    assert qs.A == [1, 4, 3, 2, 5]
    qs.PARTITION(0, 3)
    assert qs.A == [1, 2, 3, 4, 5]
    qs.PARTITION(0, 2)
    assert qs.A == [1, 2, 3, 4, 5]
    qs.PARTITION(0, 1)
    assert qs.A == [1, 2, 3, 4, 5]
Example #13
0
 def testQuickSort(self):
     s = QuickSort.Solution()
     for i in range(100):
         list_wait_to_sort = [
             random.randint(-10000, 10000) for i in range(1000)
         ]
         self.assertEqual(
             sorted(list_wait_to_sort),
             s.quickSort(list_wait_to_sort, 0,
                         len(list_wait_to_sort) - 1))
Example #14
0
def StartAlgorithm():
    global data
    if not data: return

    if (algorithmMenu.get() == 'Quick Sort'):
        QuickSort(data, 0, len(data) - 1, drawData, speedScale.get())
    elif (algorithmMenu.get() == 'Bubble Sort'):
        BubbleSort(data, drawData, speedScale.get())
    elif (algorithmMenu.get() == 'Merge Sort'):
        mergesort(data, drawData, speedScale.get())
    drawData(data, ['green' for x in range(len(data))])
    def test_sort(self):
        """tests if the sort works"""
        x = []
        for i in range(300):
            x.append(random.randint(-100, 100))
        self.sorter = QuickSort.QuickSort(x, verbose=False)

        self.sorter.sort()
        d = self.sorter.getData()
        for el in range(0, len(d) - 2):
            self.assertTrue(d[el] <= d[el + 1])
 def test_pivot(self):
     """tests if the pivot works"""
     x = []
     for i in range(300):
         x.append(random.randint(-100, 100))
     self.sorter = QuickSort.QuickSort(x, verbose=False)
     j = self.sorter.pivot(0, len(self.sorter.getData()) - 1)
     D = self.sorter.getData()
     for i in range(0, j):
         self.assertTrue(D[i] <= D[j])
     for i in range(j + 1, len(D)):
         self.assertTrue(D[j] <= D[i])
def main():
    l = randomList()
    print("List size: ", len(l))

    #BubbleSort
    start = time.time()
    BubbleSort.bubbleSort(l)
    end = time.time()
    print("BubbleSort: ", end - start)

    #InsertionSort
    start = time.time()
    InsertionSort.insertionSort(l)
    end = time.time()
    print("InsertionSort: ", end - start)

    #SelectionSort
    start = time.time()
    SelectionSort.selectionSort(l)
    end = time.time()
    print("SelectionSort: ", end - start)

    #ShellSort
    start = time.time()
    ShellSort.shellSort(l)
    end = time.time()
    print("ShellSort: ", end - start)

    #MergeSort
    start = time.time()
    MergeSort.mergeSort(l)
    end = time.time()
    print("MergeSort: ", end - start)

    #QuickSort
    start = time.time()
    QuickSort.quickSort(l, 0, len(l) - 1)
    end = time.time()
    print("QuickSort: ", end - start)
Example #18
0
def sort_test(sort_name, arr):
    import time
    start = time.time()
    if sort_name == "SelectionSort":
        import SelectionSort
        # for index in range(100):
        SelectionSort.SelectionSort.sort(arr)
    elif sort_name == "InsertionSort":
        import InsertionSort
        InsertionSort.InsertionSort.sort(arr)
    elif sort_name == "MergeSort":
        import MergeSort
        print(MergeSort.MergeSort.sort(arr))
    elif sort_name == "QuickSort":
        import QuickSort
        print(QuickSort.QuickSort().sort(arr))
    elif sort_name == "QuickSort2Ways":
        import QuickSort
        print(QuickSort.QuickSort().sort_two_ways(arr))
    if not is_sort(arr):
        raise RuntimeError(f"{sort_name} 未排序成功")
    end = time.time()
    print(f'{sort_name}, size: {len(arr)} : {end - start} s')
Example #19
0
def print_current_points_ranking(players, return_value=False):

    leaderboard_in_list = list()
    QuickSort.sort(players)

    header = '''============================
Current Tournament Rankings 
============================'''

    leaderboard_in_list.append(header)

    if not return_value:
        print(header)

    for player in players:
        line = " Name: {0} Points: {1:.2f}".format(player.name,
                                                   player.tournament_points)
        leaderboard_in_list.append(line)
        if not return_value:
            print(line)
    if (return_value):
        return leaderboard_in_list
    print()
Example #20
0
def test4():
    cur_total = 0
    data = [['a', 'z', 'r', 'c', 'g', 'e', 'a'], [1, 2, 4, 5, 3, 7],
            [56, 3, 5, -22, -4], [12.3, 122, 120.2], [1, 2, 3]]

    for el in range(5):
        queue = stu_lq.LinkedQueue()
        ans = sol_lq.LinkedQueue()
        for i in data[el]:
            queue.enqueue(i)
            ans.enqueue(i)
        if stu_qs.pick_pivot(queue) == sol_qs.pick_pivot(ans):
            cur_total += 2
            global TOTAL
            TOTAL += 2

    return f"Testcase 04: {cur_total} / 10"
Example #21
0
 def BuildTree(self, array_list, label_list, node):
     if len(array_list) == 1:
         node.data = array_list[0]
         node.label = label_list[0]
     elif len(array_list) > 1:
         keyword_index = node.depth % self.feature_dim
         left, middle, right, left_label, middle_label, right_label = mysort.MiddleArray(
             array_list, label_list, keyword_index)
         node.data = middle
         node.label = middle_label
         if len(left) > 0:
             new_node = Node.Node()
             node.add_left(new_node)
             self.BuildTree(left, left_label, new_node)
         if len(right) > 0:
             new_node = Node.Node()
             node.add_right(new_node)
             self.BuildTree(right, right_label, new_node)
Example #22
0
def main():

    #inputList = [5, 7, 10, 4, 1, 6, 8, 3]
    #inputList = [3,9,12,6]
    #inputList = [3,18,6,12,9]
    #inputList = [5,4,3,2,1]
    inputList = [22, 41, 18, 9, 8, 7, 10]
    outputList = []

    print('\nA entrada é: ', inputList)

    print('\nOrdenando com MergeSort...')

    MS.MergeSort(inputList.copy(), 0, len(inputList) - 1)

    print('\n\nA entrada é: ', inputList)
    print('\nOrdenando com QuickSort...')

    QS.QuickSort(inputList.copy(), 0, len(inputList) - 1)
Example #23
0
def main():
    #array = [6, 5, 9, 7, 5, 3, 4, 6]
    print("Unsorted Array")
    array = Generate_Int_Array(10)
    Print_Array(array)
    print()

    print("Sorted By Bubble Sort")
    array = Generate_Int_Array(10)
    Print_Array(array)
    sorted_array = Bubble_Sort(array)
    Print_Array(sorted_array)
    print()

    print("Sorted By Insertion Sort")
    array = Generate_Int_Array(10)
    Print_Array(array)
    sorted_array = Insertion_Sort(array)
    Print_Array(sorted_array)
    print()

    print("Sorted By Selection Sort")
    array = Generate_Int_Array(10)
    Print_Array(array)
    sorted_array = Selection_Sort(array)
    Print_Array(sorted_array)
    print()

    print("Sorted By Merge Sort")
    array = Generate_Int_Array(10)
    Print_Array(array)
    sorted_array = Merge_Sort(array)
    Print_Array(sorted_array)
    print()

    print("Sorted By Quick Sort")
    array = Generate_Int_Array(10)
    Print_Array(array)
    sorted_array = QuickSort(array, 0, len(array) - 1)
    Print_Array(sorted_array)
    print()
def Ordenar(vec,dist):
    Qs.quickSortHelper(vec,dist,0,len(vec)-1)
    return [vec,dist]
Example #25
0
import QuickSort



def search(list, element):
    length = len(list)
    mid =(int)(length/2)
    if(length == 0 ):
        print('Not Found')
        return 0
    print('First element ',str(list[0]),'last element ',str(list[length-1]),'mid element ',str(list[mid]))
    if list[mid] == element :
        print('element found at index =',str(mid))
        #this index is not correct as mid is specified here
        return 1
    elif list[mid] >element:
        print('Left side')
        return search(list[:mid],element)
    else:
        print('Right side')
        return search(list[mid:length],element)

l=[1,5,2,3,7,47,9,0]
s=QuickSort.sorting(l)

print(search(s.input_list,0))
Example #26
0
def main():
    print("TEST")
    node: Node = Node('A')
    node.next = Node('B')
    print(str(node))
    print()

    print("BUBBLE SORT")
    arr = [10, 3, 5, 12, 20, 9]
    BubbleSort(arr)
    print(arr)
    print()

    print("MERGE SORT")
    arr2 = [45, 12, 99, 69, 1, 13]
    MergeSort(arr2)
    print(arr2)
    print()

    print("QUICK SORT")
    arr3 = [45, 12, 99, 69, 1, 13]
    QuickSort(arr3)
    print(arr3)
    print()

    print("BINARY SEARCH")
    arr4 = [1,2,6,8,14]
    #print(BinarySearchRecursive(arr4, 2, 0, len(arr) - 1))
    print(BinarySearchIterative(arr4, 8))
    print(BinarySearchRecursive(arr4, 2, 0, len(arr4) - 1))
    print()

    graph = {
        'A': ['B', 'C', 'D', 'E'],
        'B': ['A', 'C', 'G'],
        'C': ['A', 'B', 'D'],
        'D': ['A', 'C', 'E', 'H'],
        'E': ['A', 'D', 'F'],
        'F': ['E', 'G', 'H'],
        'G': ['B', 'F'],
        'H': ['D', 'F']
    }

    # put neighbors in a reverse order for now
    graph2 = {
        'A': ['E', 'D', 'C', 'B'],
        'B': ['G', 'C', 'A'],
        'C': ['D', 'B', 'A'],
        'D': ['H', 'E', 'C', 'A'],
        'E': ['F', 'D', 'A'],
        'F': ['H', 'G', 'E'],
        'G': ['F', 'B'],
        'H': ['F', 'D']
    }

    print("BREADTH FIRST SEARCH")
    bfs(graph, 'A')
    print()

    print("DEPTH FIRST SEARCH")
    dfs(graph2, 'A')
    print()
import QuickSort as q

a = open("K1")
b = {"stem": "", "normal_form": [], "frequency": ([], [])}
for x in a:
    x = x.replace("\n", "").split(" ")
    b["stem"] = x[0]
    b["normal_form"].append(x[1])
    b["frequency"][1].append(int(x[2]))

[b["frequency"][0].append(x) for x in range(len(b["normal_form"]))]
print(b["frequency"])
q.quickSort(b["frequency"], 1, True)
print(b["frequency"])
q.quickSort(b["frequency"], 1, False)
print(b["frequency"])
Example #28
0
def randomizedPartition(array, p, r):
    i = randint(p, r)
    array[r], array[i] = array[i], array[r]
    return QuickSort.partition(array, p, r)
def sort(l):
	l = QuickSort.sort(l, f)
	#l = BubbleSort.sort(l, f)
	return l
Example #30
0
 def __FinalTransformation(self):
     """
     Сортировка словаря
     :return:
     """
     q.quickSort(self.__dct["frequency"], 1, True)
Example #31
0
for i in range(len(sizeList)):
    L = Util.generateList(sizeList[i])
    M = Util.generateSorted(sizeList[i])
    N = Util.generateReversed(sizeList[i])
    O = Util.generateSmallRange(sizeList[i])

    #listList = [L, M, N, O]
    #listNames = ['Random', 'Sorted', 'Reversed', 'SmallRange']
    listList = [L, M, O]
    listNames = ['Random', 'Sorted', 'SmallRange']
    timesList = [[], [], [], [], [], [], []]
    for x in range(len(listList)):
        #L = listList[x]
        L = Util.generateList(sizeList[i])
        A = QuickSort.QuickSort(L)
        B = HeapSort.HeapSort(L)
        C = InsertionSort.InsertionSort(L)
        D = MergeSort.MergeSort(L)
        E = PythonSorted.PythonSorted(L)
        F = SelectionSort.SelectionSort(L)
        G = RadixSort.RadixSort(L)

        sortList = [A, B, C, D, E, F, G]
        sortNames = [
            'Quick', 'Heap', 'Insertion', 'Merge', 'Python', 'Selection',
            'Radix'
        ]

        #sortList = [C]
        #sortNames = ['Insertion']
Example #32
0
def runquicktests(tests=mytests):
    for l0 in tests:
        QuickSort.quickSort(l0, 0, len(l0) - 1)
Example #33
0
#!/usr/bin/python

import random

import QuickSort

X = 0

while X <= 10000:
    print("Iteration: ", X + 1)
    n = random.choice(range(1, 1000))
    #print("n=",n)
    A = list()
    for i in range(n):
        A.append(random.choice(range(1, 10000)))

    #print("A=",A)

    B = sorted(A)
    QuickSort.QuickSort(A, 0, n - 1)

    if B != A:
        print("error")
        print("A=", A)
        print("n=", n)
        break
    else:
        X = X + 1
        continue
Example #34
0
    print("Time Taken: " + str(reverseSortedSortTime))

    outputString += "\nHeap Sort:\n"
    outputString += "Random Order: " + str(randomSortTime) + "\n"
    outputString += "Sorted Order: " + str(sortedSortTime) + "\n"
    outputString += "Reverse Sorted Order: " + str(
        reverseSortedSortTime) + "\n"
    heapSortTime[n] = (randomSortTime, sortedSortTime, reverseSortedSortTime)

    print("\nIn-place Quick Sort with Random Pivot: ")
    print("Random Order")
    runtime = 0
    for i in range(repetition):
        startTime = time.time()
        print("Start: " + str(startTime))
        quickSort = QuickSort.QuickSort(QuickSort.RANDOM_PIVOT, False)
        sortedData = quickSort.sort(data[:])
        if n < 100:
            print(data)
            print(sortedData)
        tempTime = time.time() - startTime
        print("Iteration " + str(i) + " Runtime: " + str(tempTime))
        runtime += tempTime
        print("End: " + str(time.time()))
    randomSortTime = runtime / repetition
    print("Time Taken: " + str(randomSortTime))

    print("Sorted Order")
    runtime = 0
    for i in range(repetition):
        startTime = time.time()
     print(vetor)
 elif tipo == "4":
     print(vetor)
     InsertionSort.metricas_insertionsort(vetor, "aleatório")
     InsertionSort.metricas_insertionsort(sorted(vetor, key=int), "crescente")
     InsertionSort.metricas_insertionsort(sorted(vetor, key=int, reverse=True), "decrescente")
     print(vetor)
 elif tipo == "5":
     print(vetor)
     MergeSort.metricas_mergesort(vetor, "aleatório")
     MergeSort.metricas_mergesort(sorted(vetor, key=int), "crescente")
     MergeSort.metricas_mergesort(sorted(vetor, key=int, reverse=True), "decrescente")
     print(vetor)
 elif tipo == "6":
     print(vetor)
     QuickSort.metricas_quicksort_central(vetor, 0, len(vetor)-1, "aleatório")
     QuickSort.metricas_quicksort_central(sorted(vetor, key=int), 0, len(vetor)-1, "crescente")
     QuickSort.metricas_quicksort_central(sorted(vetor, key=int, reverse=True), 0, len(vetor)-1, "decrescente")
     print(vetor)
 elif tipo == "7":
     print(vetor)
     QuickSort.metricas_quicksort_primeiro(vetor, 0, len(vetor)-1, "aleatório")
     QuickSort.metricas_quicksort_primeiro(sorted(vetor, key=int), 0, len(vetor)-1, "crescente")
     QuickSort.metricas_quicksort_primeiro(sorted(vetor, key=int, reverse=True), 0, len(vetor)-1, "decrescente")
     print(vetor)
 elif tipo == "8":
     print(vetor)
     SelectionSort.metricas_selectionSort(vetor, "aleatório")
     SelectionSort.metricas_selectionSort(sorted(vetor, key=int), "crescente")
     SelectionSort.metricas_selectionSort(sorted(vetor, key=int, reverse=True), "decrescente")
     print(vetor)
Example #36
0
#!/usr/bin/env python
# coding=utf-8

__author__ = 'iHuahua'

import QuickSort


def condition(a, b):
    if a > b:
        return True
    else:
        return False


arr = [2, 8, 7, 9, 3, 5, 6, 4, 1]
QuickSort.quick_sort(arr)
print(arr)
QuickSort.quick_sort(arr, condition)
print(arr)
Example #37
0
    i = 100
    for i in range(100, 100000, 10000):
        print i, run(i)

    # 7
    ary = "15 31 47 50 55 75 18 49 10 80".split()
    sort.insertion_sort(ary, 6)

    # 8
    ary = "80 86 11 90 84 45 14 75 85 92".split()
    aux = "80 86 11 90 84 45 14 75 85 92".split()
    MergeSort.bottom_up_merge_sort(ary, aux)

    # 9
    ary = "38 40 93 37 77 28 36 56 89 64 46 88".split()
    QuickSort.parti(ary, 0, len(ary) - 1)
    print " ".join(ary)

    # 10
    pq = PriorityQueue.PQ()
    pq.setLi("Z W R V M E F B D G".split())

    print pq
    pq.delMax()
    print pq
    pq.delMax()
    print pq
    pq.delMax()
    print pq

    # 14