Exemplo n.º 1
0
def bucketSort(tabl):
    temp = tabl

    largest = max(tabl)
    size = len(tabl)
    bucketSize = largest / size  # Difference between buckets

    buckets = [[] for i in range(size)]  # Creates 51(size) undefined tables

    for i in range(0, size):
        j = int(tabl[i] / bucketSize)
        if j != size:
            buckets[j].append(tabl[i])
        else:
            buckets[size - 1].append(tabl[i])

    index = 0

    for i in range(0, size):
        InsertionSort.insertionSort(buckets[i])

        for j in range(0, len(buckets[i])):
            temp[index] = buckets[i][j]
            index += 1

    return temp
Exemplo n.º 2
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
Exemplo n.º 3
0
 def test_ExpectedOutput(self):
     '''
     Checks if returned output is as expected.
     '''
     input_arr  = [8, 5, 2, 9, 5, 6, 3]
     output = InsertionSort.insertionSort(input_arr)
     self.assertEqual(output, [2, 3, 5, 5, 6, 8, 9])
Exemplo n.º 4
0
def InsertionSortTime(m):
    cTime = 0.0
    createData(m)
    inputList = LinkedList.LinkedList(readInData())
    cStartTime = time.time()
    c = InsertionSort.InsertionSort(inputList)
    cEndTime = time.time()
    cTime = cEndTime-cStartTime
    print("InsertionSort      : " + str(cTime))
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)
Exemplo n.º 6
0
 def InsertionSortBest(self):
     stop = False
     N = 2
     timerList = []
     while stop is not True:
         A = ArrayGen.SortedArray(N)
         start = timer()
         InsertionSort.InsertionSort(A)
         end = timer()
         timerList.append((end - start))
         if N > self.Nmax:
             stop = True
         N += 1
     return timerList
Exemplo n.º 7
0
def main():

    inputList = [5, 7, 10, 4, 1, 3, 8, 6]
    outputList = []

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

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

    outputList = IS.InsertionSort(inputList.copy())

    print(outputList)

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

    outputList = SS.SelectionSort(inputList.copy())

    print(outputList)
Exemplo n.º 8
0
 def InsertionSortWorst(self):
     stop = False
     N = 2
     Navg = 10
     timerList = []
     while stop is not True:
         avgTime = 0
         for i in range(0, Navg):
             A = ArrayGen.DecreasingArray(N)
             start = timer()
             InsertionSort.InsertionSort(A)
             end = timer()
             avgTime += (end - start)
         timerList.append(avgTime / Navg)
         if N > self.Nmax:
             stop = True
         N += 1
     return timerList
Exemplo n.º 9
0
def test_with_list(test_data):
    print('MergeSort:')
    start_time = int(round(time.time() * 1000))
    result = MergeSort.merge_sort(test_data)
    duration = int(round(time.time() * 1000)) - start_time
    print('Duration: ' + str(duration) + 'ms')
    empty_target = result
    del result
    del start_time
    del duration

    print('InsertionSort:')
    start_time = int(round(time.time() * 1000))
    result = InsertionSort.insertion_sort(test_data)
    duration = int(round(time.time() * 1000)) - start_time
    print('Duration: ' + str(duration) + 'ms')
    empty_target = result
    del result
    del start_time
    del duration

    print('BubbleSort:')
    start_time = int(round(time.time() * 1000))
    result = BubbleSort.bubble_sort(test_data)
    duration = int(round(time.time() * 1000)) - start_time
    print('Duration: ' + str(duration) + 'ms')
    empty_target = result
    del result
    del start_time
    del duration

    print('SelectSort:')
    start_time = int(round(time.time() * 1000))
    result = SelectSort.select_sort(test_data)
    duration = int(round(time.time() * 1000)) - start_time
    print('Duration: ' + str(duration) + 'ms')
    empty_target = result
    del result
    del start_time
    del duration
Exemplo n.º 10
0
    data = [random.randint(0, size) for i in range(size)]
    mp_merge_start = time.time()
    merge.process_start(data)
    mp_merge_elapsed_time = time.time() - mp_merge_start

    mp_selection_start = time.time()
    #selection calls
    mp_selection_elapsed_time = time.time() - mp_selection_start

    bubble_start = time.time()
    #bubble calls
    bubble_elapsed_time = time.time() - bubble_start

    data = [random.randint(0, size) for i in range(size)]
    insertion_start = time.time()
    InsertionSort.serialInsertionSort(data)
    insertion_elapsed_time = time.time() - insertion_start

    data = [random.randint(0, size) for i in range(size)]
    quick_start = time.time()
    quickSort.quickSort(data, 0, len(data) - 1)
    quick_elapsed_time = time.time() - quick_start

    data = [random.randint(0, size) for i in range(size)]
    merge_start = time.time()
    merge.sort(data, 0, size - 1)
    merge_elapsed_time = time.time() - merge_start

    selection_start = time.time()
    #selection calls
    selection_elapsed_time = time.time() - selection_start
Exemplo n.º 11
0
    start_time = time.time()
    # Calling bubble_sort for each data set
    BubbleSort.bubble_sort(data["data" + str(i + 1)])
    print("Bubble time for data" + str(i + 1) + " = " +
          str(time.time() - start_time))

#-----------------------------------------------------------------------------#
#                  DECREASE AND CONQUER                                  #
#-----------------------------------------------------------------------------#

#                        INSERTION SORTING
for i in range(len(data)):
    # invoke the start time to measure the performance
    start_time = time.time()
    # Calling bubble_sort for each data set
    InsertionSort.insertion_sort_iterative(data["data" + str(i + 1)])
    print("Insertion time for data" + str(i + 1) + " = " +
          str(time.time() - start_time))

#-----------------------------------------------------------------------------#
#                        DIVIDE AND CONQ SORTING                         #
#-----------------------------------------------------------------------------#

#                        MERGE SORTING
for i in range(len(data)):
    # invoke the start time to measure the performance
    start_time = time.time()
    # Calling bubble_sort for each data set
    MergeSort.merge_sort(data["data" + str(i + 1)])
    print("Merge time for data" + str(i + 1) + " = " +
          str(time.time() - start_time))
Exemplo n.º 12
0
import QuickSort
import MergeSort
import InsertionSort
import SelectionSort

if __name__ == '__main__':
    l = [2, 7, 3, 1, 0, 11, 9, 8]
    QuickSort.quickSort(l)
    MergeSort.mergeSort(l)
    InsertionSort.insertionSort(l)
    SelectionSort.selectionSort(l)
    print(l)
    comparisons, exchanges = HeapSort.heap_sort(B)

    total_time = timeit.default_timer() - start_time
    print("Total comparisons are ", comparisons, " and total exchanges are ",
          exchanges)

    print("Total time taken is ", total_time)

    print("---------Insertion Sort---------")

    B = A.copy()

    start_time = timeit.default_timer()

    comparisons, exchanges = InsertionSort.insertion_sort(B)

    total_time = timeit.default_timer() - start_time

    print("Total comparisons are ", comparisons, " and total exchanges are ",
          exchanges)

    print("Total time taken is ", total_time)

    print("---------Merge Sort (Recursive)--------")

    B = A.copy()

    start_time = timeit.default_timer()

    B, comparisons, exchanges = MergeSortRecursive.merge_sort(B)
Exemplo n.º 14
0
 def apply_sort(self, list_of_things):
     return InsertionSort.insertion_sort(list_of_things)
Exemplo n.º 15
0
def test(name, number):
    A = []
    for n in range(100, 10100, 100):
        for k in range(0, number):
            array = np.random.randint(0, 1000, n)
            array1 = array.copy()
            array2 = array.copy()
            array3 = array.copy()
            array4 = array.copy()
            array5 = array.copy()
            array6 = array.copy()

            start = time.time()
            comparing, changes = IS.insertionSort(array1)
            end = time.time()
            timer = end - start

            data = {
                "Tablica": n,
                "Czas": timer,
                "Zmiany": changes,
                "Porownania": comparing,
                "Nazwa": "Insert"
            }
            A.append(data)

            start = time.time()
            comparing, changes = MS.mergeSort(array2)
            end = time.time()
            timer = end - start

            data = {
                "Tablica": n,
                "Czas": timer,
                "Zmiany": changes,
                "Porownania": comparing,
                "Nazwa": "Merge"
            }
            A.append(data)

            start = time.time()
            comparing, changes = QS.quickSort(array3, 0, len(array3) - 1)
            end = time.time()
            timer = end - start

            data = {
                "Tablica": n,
                "Czas": timer,
                "Zmiany": changes,
                "Porownania": comparing,
                "Nazwa": "Quick"
            }
            A.append(data)

            start = time.time()
            comparing, changes = H.megreInsertSort(array4)
            end = time.time()
            timer = end - start

            data = {
                "Tablica": n,
                "Czas": timer,
                "Zmiany": changes,
                "Porownania": comparing,
                "Nazwa": "Hibrid10"
            }
            A.append(data)

            start = time.time()
            comparing, changes = DP.DualPivot(array, 0, len(array5) - 1)
            end = time.time()
            timer = end - start

            data = {
                "Tablica": n,
                "Czas": timer,
                "Zmiany": changes,
                "Porownania": comparing,
                "Nazwa": "Dual"
            }
            A.append(data)

    try:
        file = open(name, "w")
        json.dump(A, file, indent=3)
    except IOError:
        pass
    finally:
        file.close()
Exemplo n.º 16
0
import time
import random
import InsertionSort, MergeSort

if __name__ == "__main__":
    array_size = 10000
    arr = random.sample(range(1, 10001), array_size)
    arr_2 = list(arr)

    start_merge = time.time()
    MergeSort.merge_sort(arr)
    end_merge = time.time()

    start_insertion = time.time()
    InsertionSort.insertion_sort(arr_2)
    end_insertion = time.time()

    print("Merge sort :  %s seconds" % (end_merge - start_merge))
    print("Insertion sort :  %s seconds" % (end_insertion - start_insertion))
Exemplo n.º 17
0
start = datetime.datetime.now()
arr1 = SelectionSort(arr1)
selectionSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr2 = SelectionSort(arr2)
selectionSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr3 = SelectionSort(arr3)
selectionSortTimings.append(str(datetime.datetime.now() - start))
sortingTimeTableArray.append(selectionSortTimings)

# Insertion sorted
print("Insertion sorted - Random  Best Case  Worst Case")
insertionSortTimings = ["Insertion Sort   "]
start = datetime.datetime.now()
arr4 = InsertionSort(arr4)
insertionSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr5 = InsertionSort(arr5)
insertionSortTimings.append(str(datetime.datetime.now() - start))
start = datetime.datetime.now()
arr6 = InsertionSort(arr6)
insertionSortTimings.append(str(datetime.datetime.now() - start))
sortingTimeTableArray.append(insertionSortTimings)

# Bubble sorted
print("Bubble sorted - Random  Best Case  Worst Case")
bubbleSortTimings = ["Bubble Sort      "]
start = datetime.datetime.now()
arr7 = BubbleSort(arr7)
bubbleSortTimings.append(str(datetime.datetime.now() - start))
 def test_CorrectInput(self):
     '''
     Checks if input is correct.
     '''
     output = InsertionSort.InsertionSort(123)
     self.assertEqual(output, -1)
 def test_TestOutputArray(self):
     '''
     Checks if array is sorted.
     '''
     output = InsertionSort.InsertionSort([3,4,2,5,1])
     self.assertEqual(output, [1,2,3,4,5])
Exemplo n.º 20
0
def test_insertionsort3():
    ins = InsertionSort.Array([1])
    ins.INSERTION_SORT()
    assert ins.A == [1]
Exemplo n.º 21
0
    cds.worst(x)
    cds.worstCaseOfMixed(x)
    cds.sameValues(x)
    cds.sameValues2(x)
    cds.sameValues3(x)

print("For Insertion Sort graph please choose 1:")
print("For Merge Sort graph please choose 2:")
print("For Quick Sort graph please choose 3:")
print("For Heap Sort graph please choose 4:")
print("For Count Sort graph please choose 5:")
print("For a comparative graph of all algorithms, please choose 6:")

choose = input()
if choose == "1":
    ins.Insertion()
    ins.generateCases()

elif choose == "2":
    ms.Merge()
    ms.generateCases()

elif choose == "3":
    qs.Quick()
    qs.generateCases()

elif choose == "4":
    hs.Heap()
    hs.generateCases()

elif choose == "5":
Exemplo n.º 22
0
    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"
Exemplo n.º 23
0
    start = time.time()
    SelectionSort.selection_sort(test_list)
    finish = time.time()
    print("********************************")
    print("SelectionSort: ", test_list)
    print("time: %f" % (finish - start))
    print("\n")

    test_list = [
        1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37,
        54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3,
        45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19,
        4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67
    ]
    start = time.time()
    InsertionSort.insertion_sort(test_list)
    finish = time.time()
    print("********************************")
    print("InsertionSort: ", test_list)
    print("time: %f" % (finish - start))
    print("\n")

    test_list = [
        1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3, 45, 68, 125, 37,
        54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19, 4234, 100, 2, 3,
        45, 68, 125, 37, 54614, 2, 46, 67, 1, 5, 52, 4, 23, 1, 32, 4, 5, 6, 19,
        4234, 100, 2, 3, 45, 68, 125, 37, 54614, 2, 46, 67
    ]
    size = len(test_list)
    start = time.time()
    QuickSort.quick_sort(test_list, 0, size - 1)
Exemplo n.º 24
0
    for i in range(0, size):
        tabl.append(random.randrange(100))
        
        
tabl = [30]
init(tabl, 30)

print(tabl)

print("Selection sort: \n")
temp = SelectionSort.selectionSort(tabl)
print(temp)
print("\n\n")

print("Insertion sort: \n")
temp = InsertionSort.insertionSort(tabl)
print(temp)
print("\n\n")

print("Bubble sort: \n")
temp = BubbleSort.bubbleSort(tabl)
print(temp)
print("\n\n")

print("Quick sort: \n")
temp = QuickSort.quickSort(tabl)
print(temp)
print("\n\n")

print("Merge sort: \n")
temp = MergeSort.mergeSort(tabl)
     print(vetor)
 elif tipo=="2":
     print(vetor)
     BubbleSort.metricas_bubblesort_melhorado(vetor, "aleatório")
     BubbleSort.metricas_bubblesort_melhorado(sorted(vetor, key=int), "crescente")
     BubbleSort.metricas_bubblesort_melhorado(sorted(vetor, key=int, reverse=True), "decrescente")
     print(vetor)
 elif tipo=="3":
     print(vetor)
     HeapSort.metricas_heapsort(vetor, "aleatório")
     HeapSort.metricas_heapsort(sorted(vetor, key=int), "crescente")
     HeapSort.metricas_heapsort(sorted(vetor, key=int, reverse=True), "decrescente")
     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)
Exemplo n.º 26
0
import SelSort as sv
import BubbleSort as bs
import InsertionSort as ins

print("Script running")
print("Please select the Sort you want to see:")
print("1) Selection Sort")
print("2) Bubble Sort")
print("3) Insertion Sort")

x = input()

if x == '1':
    sv.main()
elif x == '2':
    bs.main()
elif x == '3':
    ins.main()
else:
    print('Wrong Choice')
Exemplo n.º 27
0
    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']

        for j in range(len(sortList)):
Exemplo n.º 28
0
def test_insertionsort1():
    ins = InsertionSort.Array(
        [1, 7, 6, 5, 4, 3, 2, 12, 11, 65, 45, 34, 22, 19, 78, 101])
    ins.INSERTION_SORT()
    assert ins.A == [1, 2, 3, 4, 5, 6, 7, 11, 12, 19, 22, 34, 45, 65, 78, 101]
Exemplo n.º 29
0
import BubbleSort
list = [1, 5, 2, 35, 7, 3, 4]
print("Data yang di sort", list)
print("Bubble Sort:")
BubbleSort.bubblesort(list)
print('=============================')
import InsertionSort
list = [2, 54, 38, 76, 23, 56, 84, 90]
print('Data yang akan di sort :', list)
print('Insertion Sort :')
InsertionSort.insertion(list)
print('=============================')
import mergesort
list = [2, 5, 60, 43, 27, 10, 89, 17]
print('Data yang akan di sort :', list)
print('Merge Sort :')
mergesort.ms(list)
print('=============================')
import quickshort
a = [68, 90, 78, 44, 34, 20, 100, 56, 34, 2]
print('Data yang akan di sort :', list)
print('Quick Sort :')
quickshort.quickshort(a, 0, len(a) - 1)
print('=============================')
import SelectionSort

lis = [54, 26, 93, 17, 77, 31, 44, 55, 20, 21, 34, 65, 70]
print('Data yang akan di sort :', list)
print('Selection Sort :')
SelectionSort.selection(list)
Exemplo n.º 30
0
import InsertionSort as Is

lst = []
size = eval(input('Enter the size of the list: '))
for i in range(size):
    n = int(input('Enter the number: '))
    lst.append(n)
print('Before sorting list is: ', lst)
Is.Inssort(lst)
print('After sorting list is: ', lst)