def makeArrayConsecutive(sequence):
    #    """
    #    First solution with time complexity O(n^2)
    #    in: array of int
    #    out: a sorted array of int containing missing digits
    #    Find a set in a way that its union with sequence contains every integer missing from the array
    #
    #    1. sort the input array
    #        a. use heap or merge sort (both have O(nlgn) time complexity)
    #    2. create an array to store missing elements, called it missing_items
    #    3. iterate over the sequence array, repeat following steps for each item in the array
    #        a. use current item as min and next item as max
    #        b. make a range from min and max while excluding min and max
    #        c. append the result in missing_items
    #    4. return missing_items array
    #    """
    #    mergeSort(sequence)
    #    missing_items = []
    #    for i in range(len(sequence)):
    #        mi = sequence[i]
    #        if sequence[i] != sequence[-1]: ## check if we are not at the last index
    #            ma = sequence[i+1]
    #        else:
    #            break ## if last index is reached break out of the for loop
    #        res = [x for x in range(mi+1, ma)] ## make a range between min and max while excluding min and max
    #        if res: ## if res is not empty and there are digits between min and max, then add it to the result
    #            ## in python the order with which we union the arrays will be preserved in the result array, hence we do not need to sort it again
    #            missing_items += res
    #    return missing_items
    """
    Second solution with time complexity: O(2n)
    1. sort the array and call it sorted_array 
    2. create a new array called missing_items
    3. create a dictionary called it my_dict
    4. iterate over the items in the input array
    5. use the array items as the dictionary keys with value is equal to True
    6. iterate over the range from first to the last item in sorted_array
        try to access the dictionary if the key (item) exist
        if the key does not exist, append the item to the result
    7. return result
    """
    mergeSort(sequence)
    missing_items = []
    my_dict = {}
    for x in sequence:
        my_dict[x] = True

    for i in range(sequence[0], sequence[-1]):
        try:
            if my_dict[i]:
                pass

        except KeyError:
            missing_items.append(i)
    return missing_items
Exemple #2
0
def start():
    global data

    if var.get() == OptionList[0]:
        bub_sort(data, drawdata, speed.get())
    if var.get() == OptionList[1]:
        mergeSort(data, 0, int(data_size.get()) - 1, drawdata, speed.get())
    if var.get() == OptionList[2]:
        insertionSort(data, drawdata, speed.get())
    if var.get() == OptionList[3]:
        quickSort(data, 0, int(data_size.get()) - 1, drawdata, speed.get())
Exemple #3
0
def sortAndTimeList(some_list):
	#insert sort
	start_time = time.time()
	insertSort(list(some_list))
	insert_sort_time = round(((time.time() - start_time) * 1000), 4) # converts to milliseconds and rounds to 4 decimals

	#merge sort
	start_time = time.time()
	mergeSort(list(some_list))
	merge_sort_time = round(((time.time() - start_time) * 1000), 4) # converts to milliseconds and rounds to 4 decimals

	times = [insert_sort_time, merge_sort_time]
	return times
def calculateDistance(user_x, user_y, canteen):
    # Create an empty list to append unsorted canteen names and their linear distances from the user
    canteen_distance_unsorted = []

    # Loop to extract location of each canteen
    for ID in list(canteen.keys()):
        # Extract x-coordinate of canteen looped from canteen database
        canteen_x = canteen[ID]["x_coordinate"]

        # Extract y-coordinate of canteen looped from canteen databse
        canteen_y = canteen[ID]["y_coordinate"]

        # Calculate the horizontal component of the distance between the user and the canteen looped
        distance_x = abs(user_x - canteen_x)

        # Calculate the vertical component of the distance between the user and the canteen looped
        distance_y = abs(user_y - canteen_y)

        # Calculate the total linear distance between the user and the canteen looped
        distance = sqrt(distance_x**2 + distance_y**2)

        # Append canteen name and its linear distance from the user into a list
        canteen_distance_unsorted.append([canteen[ID]["name"], distance])

    # Sort list by distances (ascending)
    canteen_dist_sorted = mergeSort(canteen_distance_unsorted)

    # Return the sorted list of canteen names and their linear distances from the user
    return canteen_dist_sorted
Exemple #5
0
def methodTester(sortMethod, baseSize=10):

    #store the sorted file names
    sorted_files = []

    # Create the random number files
    files = _fileCreator(baseSize)

    # Create the time table file
    timing_file = open(str(sortMethod) + "Sort_test_times", 'w')
    timing_file.write("Input Size (n):	Time cost:")

    # For each of the files:
    for file in files:

        # Create a list from the numbers stored in the file
        number_list = _fileToList(file)
        number_count = len(number_list)
        for i in range(number_count):
            number_list[i] = float(number_list[i])

        # Create the file to store the sorted list
        sortedFileName = str(file) + "_" + sortMethod + "sort_sorted"
        sorted_files.append(sortedFileName)
        sortedFile = open(sortedFileName, 'w')

        # Check sorting method, then sort while timing
        if sortMethod == 'merge':
            start_time = time.time()
            numberListSorted = mSort.mergeSort(number_list, 1,
                                               len(number_list))
            stop_time = time.time()
        elif sortMethod == 'quick':
            start_time = time.time()
            numberListSorted = qSort.quickSort(number_list, 0,
                                               len(number_list) - 1)
            stop_time = time.time()
        elif sortMethod == 'insertion':
            start_time = time.time()
            numberListSorted = iSort.insertionSort(number_list,
                                                   len(number_list))
            stop_time = time.time()
        else:
            print('''Uh oh, the provided sort method has yet to be implemented!
Please use either 'merge', 'quick', or 'insertion'.\n''')

        # Store the sorted list in its respective file
        sortedFile.write(str(numberListSorted))
        sortedFile.close()

        # Calculate the time taken, then add it to the timing file
        sort_time = stop_time - start_time
        timing_file.write("\n" + str(number_count) + "		" + str(sort_time))

    # Close the timing file, and prompt the user on whether
    #  or not to delete the created files used to calculate
    #  the timing data.
    timing_file.close()
    files.extend(sorted_files)
    _askDelete(files)
Exemple #6
0
def main():
    L = readInput()

    while True:
        s = raw_input('sort by firstname or lastname, enter <f/l>: ')
        if s == 'f' or s == 'l':
            break
        else:
            print 'wrong option - please try again!'
    if s == 'f':
        sl = merge_sort.mergeSort(L, firstLastName)
        print 'list sorted on first name: '
        print sl
    else:
        sl = merge_sort.mergeSort(L, lastFirstName)
        print 'list sorted on second name: '
        print sl
def compare_merge_insert():
    N = 10**4  # change here to change array size. 10**4 is enough big, it takes about 5 seconds.
    arr_insert = [random.randint(0, 10**6) for _ in range(N)]
    arr_merge = copy.deepcopy(arr_insert)
    start_time = time.time()
    insertion_sort.insertionSort(arr_insert)
    insert_time = time.time() - start_time
    start_time = time.time()
    merge_sort.mergeSort(arr_merge)
    merge_time = time.time() - start_time

    # check error
    for i, n in enumerate(arr_insert):
        if n != arr_merge[i]:
            print("Error: result is not the same!, ", i)
            return
    print("result is the same")
    print("insert sort time = ", insert_time)
    print("merge  sort time = ", merge_time)
Exemple #8
0
def kruskal(G, *args):
    # Inizializzo un grafo vuoto, ovvero con un numero di vertici vuoti uguale a G, per evitare l'uscita dai limiti
    # durante l'assegnazione del valore dei vertici. Viene inoltre convertita la lista di archi a deque, per favorire
    # l'operazione di pop ed aggiunta archi.
    G.initialize()
    A = Graph(G.n_vertexes)
    # L'algoritmo di merge sort qui utilzzato ha complessità O(n*log(n)), come previsto.
    mergeSort(G.arch_list)
    for e in G.arch_list:
        # Viene aggiunto un arco al grafo dell'MST.
        if e.vert1 != e.vert2:
            r1 = G.find(e.vert1)
            r2 = G.find(e.vert2)
            if r1 != r2:
                A.add(e.vert1, e.vert2, e.weight)
                G.union(r1, r2)
            # Ottimizzazione suggerita a lezione, per una terminazione anticipata dell'algoritmo.
            if A.n_arches == G.n_vertexes - 1:
                break
    return A
def kruskalNaive(G, *args):
    # Inizializzo un grafo vuoto, ovvero con un numero di vertici vuoti uguale a G, per evitare l'uscita dai limiti
    # durante l'assegnazione del valore dei vertici. Viene inoltre convertita la lista di archi a deque, per favorire
    # l'operazione di pop ed aggiunta archi.
    A = Graph(G.n_vertexes)
    A.arch_list = deque()
    # L'algoritmo di merge sort qui utilzzato ha complessità O(n*log(n)), come previsto.
    mergeSort(G.arch_list)
    for e in G.arch_list:
        # Viene aggiunto un arco al grafo dell'MST, solo se non si tratta di un self loop, altrimenti viene ignorato.
        if e.vert1 != e.vert2:
            A.add(e.vert1, e.vert2, e.weight)
            visited = [False] * G.n_vertexes
            # È stato scelto l'algoritmo DFS per il controllo sulla ciclicità del grafo.
            if dfs_iter(A, e.vert1, visited):
                # Qualora il grafo fosse ciclico, viene rimosso l'ultimo arco aggiunto.
                A.pop()
            # Ottimizzazione suggerita a lezione, per una terminazione anticipata dell'algoritmo.
            if A.n_arches == G.n_vertexes - 1:
                break
    return A
def sorting_algorithms(arrayToBeSorted):
    # Calling Insertion sort and calculating time elapsed
    print("\n\n*********INSERTION SORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted1 = list(arrayToBeSorted)
    #print(arrayToBeSorted1)
    startTime1 = datetime.datetime.now()
    sorted_array = insertion_sort.insertionSort(arrayToBeSorted1)
    endTime1 = datetime.datetime.now()
    diff = endTime1 - startTime1
    timeElapsed1 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after Insertion sort is:")
    #print(sorted_array)
    print("\nTime elapsed in milliseconds after Insertion sort is : ")
    print(timeElapsed1)

    # Calling merge sort and calculating time elapsed
    print("\n\n\n*********MERGE SORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted2 = list(arrayToBeSorted)
    #print(arrayToBeSorted2)
    n = len(arrayToBeSorted2)
    startTime2 = datetime.datetime.now()
    merge_sort.mergeSort(arrayToBeSorted2, 0, n - 1)
    endTime2 = datetime.datetime.now()
    diff = endTime2 - startTime2
    timeElapsed2 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after merge sort is")
    #print (arrayToBeSorted2)
    print("\n\nTime elapsed in milliseconds after Merge-sort is : ")
    print(timeElapsed2)

    # Calling In-place quicksort sort and calculating time elapsed
    print("\n\n\n*********IN-PLACE QUICKSORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted3 = list(arrayToBeSorted)
    #print(arrayToBeSorted3)
    n = len(arrayToBeSorted3)
    startTime3 = datetime.datetime.now()
    inplace_quicksort.quickSort(arrayToBeSorted3, 0, n - 1)
    endTime3 = datetime.datetime.now()
    diff = endTime3 - startTime3
    timeElapsed3 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after In-place quicksort is:")
    #print (arrayToBeSorted3)
    #for i in range(n):
    #print ("%d" %arrayToBeSorted3[i]),
    print("\n\nTime elapsed in milliseconds after Quicksort is : ")
    print(timeElapsed3)

    # Calling Modified Quicksort and calculating time elapsed
    print("\n\n\n*********MODIFIED QUICKSORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted4 = list(arrayToBeSorted)
    #print(arrayToBeSorted4)
    n = len(arrayToBeSorted4)
    startTime4 = datetime.datetime.now()
    modified_quicksort.quickSort(arrayToBeSorted4, 0, n - 1)
    endTime4 = datetime.datetime.now()
    diff = endTime4 - startTime4
    timeElapsed4 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after Modified quicksort is:")
    #print (arrayToBeSorted4)
    print("\n\nTime elapsed in milliseconds after Modified Quicksort is : ")
    print(timeElapsed4)
import random

from merge_sort import mergeSort


def checkSumofNumbers(dataList, num):
    i = 0
    j = len(dataList) - 1
    while (i < j):
        if (dataList[i] + dataList[j]) == num:
            return i, j
        elif (dataList[i] + dataList[j]) > num:
            j -= 1
        elif (dataList[i] + dataList[j]) < num:
            i += 1
    return None, None


if __name__ == "__main__":
    dataList = [-4, 40, 62, 39, 21, -61, 68, 31, 10, 1]
    dataList = mergeSort(dataList)
    num = 41
    print("Sorted list: {} search for sum: {}".format(dataList, num))
    result = checkSumofNumbers(dataList, num)
    print(result)
Exemple #12
0
def doQuestion(question):
    """
    Executa as operações para a questão indicada.
    """

    global g_y0, g_ylim

    if question == 1:  # Questão #1
        g_ylim = 10
        plotItem('1a')
        plotItem('1b')
        plotItem('1c')
        plotItem('1d')
        plotItem('1e')
        plotItem('1f')
        plotItem('1g')
        plotItem('1h')

    elif question == 2:
        g_ylim = 1000
        plotItem('2a')
        plotItem('2b')
        g_ylim = 10
        plotItem('2c')
        g_ylim = 10000
        plotItem('2d-O')
        g_ylim = 1000
        plotItem('2d-Ω')

    elif question == 5:
        import random
        candidatos = [
            'Joaquim José da Silva Xavier',
            'Pedro Álvares de Alencar',
            'Luiz C Bonaparte Peixoto',
            'Claudio Emanuel da Silva',
        ]
        cumpridos = random.sample(range(100), 4)
        cumpridos[3] = cumpridos[1]  # adiciona um repetido.
        tempos = random.sample(range(100), 4)
        #tempos[2] = tempos[0]       # adiciona um repetido.
        tempos[3] = tempos[1]  # adiciona um repetido.
        #tempos = cumpridos = [0,0,0,0]
        print(
            'Avaliando os candidatos, algoritmos executados e tempos respectivos:'
        )
        for k, n in enumerate(candidatos):
            print('{} \t\t- {} em {}t'.format(n, cumpridos[k], tempos[k]))
        q5avaliador(candidatos, cumpridos, tempos)

    elif question == 6:
        import random
        a = random.sample(range(100), 50)
        i = q6recmenor(a)
        print('Índice encontrado: {} com valor {}'.format(i, a[i]))
        sort.mergeSort(a)
        print(a[0])

    elif question == 0:
        g_y0, g_ylim = -100, 100
        plotItem('01')
Exemple #13
0
def test_sort3():
    arr = [5, 12, 7, 5, 5, 7]
    actual = mergeSort(arr)
    expected = [5, 5, 5, 7, 7, 12]
    assert actual == expected
Exemple #14
0
def test_sort2():
    arr = [20, 18, 12, 8, 5, -2]
    actual = mergeSort(arr)
    expected = [-2, 5, 8, 12, 18, 20]
    assert actual == expected
 def test_basic(self, rst, nums):
     self.assertEqual(rst, mergeSort(nums))
Exemple #16
0
def test_sort4():
    arr = [2, 3, 5, 7, 13, 11]
    actual = mergeSort(arr)
    expected = [2, 3, 5, 7, 11, 13]
    assert actual == expected
 def test_big_input(self, rst, nums):
     self.assertEqual(rst, mergeSort(nums))
Exemple #18
0
def testSort(tests, n, minimum, maximum):
    time = [datetime.timedelta(0)] * 6
    for i in range(tests):
        ar = createArray(n, minimum, maximum)

        i_sort = list(ar)
        m_sort = list(ar)
        q_sort = list(ar)
        qr_sort = list(ar)
        h_sort = list(ar)

        d = datetime.datetime.now()
        insertion_sort.insertionSort(i_sort)
        time[0] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        m_sort = merge_sort.mergeSort(m_sort)
        time[1] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        quick_sort.quickSort(q_sort)
        time[2] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        quick_sort.quickSortRand(qr_sort)
        time[3] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        h_sort = heap_sort.heapSort(h_sort)
        time[4] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        bible = sorted(ar)
        time[5] += (datetime.datetime.now() - d)

        error = False
        if not compareArrays(bible, i_sort):
            print "Insertion sort error: ar =", ar, ", i_sort =", i_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, m_sort):
            print "Merge sort error: ar =", ar, ", m_sort =", m_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, q_sort):
            print "Quick sort (deterministic) error: ar =", ar, ", q_sort =", q_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, qr_sort):
            print "Quick sort (random) error: ar =", ar, ", qr_sort =", qr_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, h_sort):
            print "Heap sort error: ar =", ar, ", h_sort =", h_sort, ", bible =", bible
            error = True

        if not error:
            print "Test", i + 1, "successful"

    print "Insertion sort time =", time[0]
    print "Merge sort time =", time[1]
    print "Quick sort (deterministic) time =", time[2]
    print "Quick sort (random) time =", time[3]
    print "Heap sort time =", time[4]
    print "Default Python sort time =", time[5]
Exemple #19
0
def test_sort1():
    arr = [8, 4, 23, 42, 16, 15]
    actual = mergeSort(arr)
    expected = [4, 8, 15, 16, 23, 42]
    assert actual == expected
from bubble_sort import bubbleSort
from normalise_list import normalise

import matplotlib.pyplot as plt
from timeit import timeit
from random import randint

listSize = 1000

#Generate a large random list
print("Generating list...")
listToSort = [randint(0, 1000) for i in range(listSize)]

#Create anonymous functions to use with timeit
bs = lambda: bubbleSort(listToSort)
ms = lambda: mergeSort(listToSort)
bis = lambda: sorted(listToSort)

print("Timing sorting algorithms...")
#Time the function for 100 runs each
mergeTime = timeit(ms, number=100)

bubbleTime = timeit(bs, number=100)

builtInTime = timeit(bis, number=100)

#Assemble times into a list for plotting a graph
times = [mergeTime, bubbleTime, builtInTime]

#Get units for time
units = ["seconds", "milliseconds", "microseconds", "nanoseconds"]
from merge_sort import mergeSort

import random
from time import time
import matplotlib.pyplot as plt

size = []
t = []
n = 1000000
for i in range(n, n * 10, n):
    randomvalues = random.sample(range(i), i)
    start_time = time()
    mergeSort(randomvalues, 0, len(randomvalues) - 1)
    end_time = time()
    total_time = end_time - start_time

    size.append(i)
    t.append(total_time)

print(size)
print(t)
plt.plot(size, t)
plt.show()