Exemple #1
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
 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)
Exemple #3
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)
Exemple #4
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])
Exemple #7
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')
Exemple #8
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)
Exemple #9
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()
Exemple #10
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']
#!/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
Exemple #12
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()
Exemple #13
0
 def solution2(self, arr, k):
     QuickSort().quickSort(arr, 0, len(arr) - 1)
     print(arr)
Exemple #14
0
import TestHelper
import MergeSort
import QuickSort
import heapSort
from time import time

l = TestHelper.CreateRandomIntList(100000, 10, 9000000)
lc = list(l)
t0 = time()

qck = QuickSort.QuickSort(l)
t1 = time()
s = MergeSort.MergeSort(l)
t2 = time()
heapSort.heapSort(lc)
t3 = time()
print((l[99], s[99]))
print((l[99], qck[99]))
print((l[99], lc[99]))

print('function vers1 takes %f' % (t1 - t0))
print('function vers2 takes %f' % (t2 - t1))
print('function vers3 takes %f' % (t3 - t2))
import random
import QuickSort as q
import RadixSort as c
import time

n = [n for n in range(10000)]
random.shuffle(n)

sort1 = q.QuickSort(n)

t = time.time()
sort1.sort()
print('Quicksort time taken: %s' % str(time.time() - t))

random.shuffle(n)
sort2 = c.RadixSort(n)

t = time.time()
sort2.sort()
print('Radix sort time taken: %s' % str(time.time() - t))
Exemple #16
0
# coding=utf-8

import InsertSort
import MergeSort
import QuickSort
import BubbleSort
import HeapSort
import random
import os

if __name__ == "__main__":
    os.system("cls")
    arr = []
    count = int(1e2)
    for i in range(count):
        arr.append(random.random())
    print("开始对各个排序算法进行性能测试,测试用的数据量大小为{}个浮点数".format(count))
    a = arr.copy()
    QuickSort.QuickSort(a)
    a = arr.copy()
    MergeSort.MergeSort(a)
    a = arr.copy()
    HeapSort.HeapSort(a)
    a = arr.copy()
    InsertSort.InsertSort(a)
    a = arr.copy()
    BubbleSort.BubbleSort(a)
Exemple #17
0
 def test_TestOutputArray(self):
     '''
     Checks if array is sorted.
     '''
     output = QuickSort.QuickSort([3, 4, 2, 5, 1])
     self.assertEqual(output, [1, 2, 3, 4, 5])
 def test_empty(self):
     """sorting of empty list is empty"""
     self.assertEqual(QuickSort.QuickSort([]).getData(), [])
start = datetime.datetime.now()
arr7 = BubbleSort(arr7)
bubbleSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr8 = BubbleSort(arr8)
bubbleSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr9 = BubbleSort(arr9)
bubbleSortTimings.append(str(datetime.datetime.now() - start))
sortingTimeTableArray.append(bubbleSortTimings)

# QuickSort sorted
print("Quick sorted - Random  Best Case  Worst Case")
quickSortTimings = ["Quick Sort       "]
start = datetime.datetime.now()
arr10 = QuickSort(arr10, 0, N - 1)
quickSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr11 = QuickSort(arr11, 0, N - 1)
quickSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr12 = QuickSort(arr12, 0, N - 1)
quickSortTimings.append(str(datetime.datetime.now() - start))
sortingTimeTableArray.append(quickSortTimings)

# Merge sorted
print("Merge sorted - Random  Best Case  Worst Case")
mergeSortTimings = ["Merge Sort       "]
start = datetime.datetime.now()
arr13 = MergeSort(arr13)
mergeSortTimings.append(str(datetime.datetime.now() - start))
Exemple #20
0
 def test_quicksort(self):
     data1 = [10, 9, -1, 0, 4, 7, 8]
     ret = data1
     QuickSort(data1)
     sorted(ret)
     self.assertEqual(ret, data1)
Exemple #21
0
 def test_CorrectInput(self):
     '''
     Checks if input is correct.
     '''
     output = QuickSort.QuickSort(123)
     self.assertEqual(output, -1)
Exemple #22
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()
    if num != "X":
        LI.append(int(num))
    else:
        terminate = True

print "\nThe Entered List is: ", LI

print "\nPlease Choose any one of the following Sorting Algorithms: \n1.Bubble Sort \n2.Selection Sort \n3.Insertion Sort \n4.Quick Sort \n5.Merge Sort"
choice = int(raw_input(">>"))

if choice == 1:
    print "\nSorting the List using Bubble Sort..."
    BubbleSort.BubbleSort(LI)
elif choice == 2:
    print "\nSorting the List using Selection Sort..."
    SelectionSort.SelectionSort(LI)
elif choice == 3:
    print "\nSorting the List using Insertion Sort..."
    InsertionSort.InsertionSort(LI)
elif choice == 4:
    print "\nSorting the List using Quick Sort..."
    QuickSort.QuickSort(LI)
elif choice == 5:
    print "\nSorting the List using Merge Sort..."
    MergeSort.MergeSort(LI)
else:
    print "\nSorry Wrong Selection!!!"
    print "BYE!!!"
    exit()

print "\nThe Sorted List is : ", LI, "\n"