Beispiel #1
0
 def test_merge_sort_one_element(self):
     array = random.sample(range(1, 100), 1)
     array_duplicate = array[:]
     merge = MergeSort(array)
     self.assertIsNotNone(merge.array)
     self.assertEqual(len(merge.array), 1)
     array_duplicate.sort()
     merge.merge_sort_algorithm(0, len(merge.array) - 1)
     self.assertEqual(merge.array, array_duplicate)
 def testmergesort(self):
     print('main')
     A = [random.randint(-100,100) for c in range(100000)]
     print('before sort',A)
     MergeSort.sort(A)
     print('after sort', A)
     for i in range(len(A)-1):
         if A[i] > A[i+1]:
             self.fail('Error in Merge Sort')
Beispiel #3
0
def SortPoints(points):
    Px = MergeSort(points)
    swapped_points = []
    for i in range(0, len(points)):
        swapped_points.append([points[i][1], points[i][0]])
    prePy = MergeSort(swapped_points)
    Py = []
    for i in range(0, len(prePy)):
        Py.append([prePy[i][1], prePy[i][0]])
    return Px, Py
Beispiel #4
0
def run_merge_sort():
    ll = np.random.randint(-10, 10, 10)  #[7, 6, 5, 4, 3, 2, 1]
    print(ll)
    _is = MergeSort(ll)
    res = _is.sort()
    print("MergeSort")
    print()
    print(f"before: {ll}")
    print(f"after: {res}")
    print()
 def test_merge_sort(self) -> None:
     elements: List[int] = []
     #random.seed(a=1)
     elements = [random.randrange(0, 101) for _ in range(100)]
     #elements = [96, 90, 85, 78, 81, 97, 14, 29, 73, 84]
     print('Elements are :{}'.format(elements))
     ms = MergeSort(elements)
     sorted_elements = ms.sort()
     print('Elements after sorting are : {}'.format(elements))
     elements.sort()
     self.assertEqual(elements, sorted_elements)
Beispiel #6
0
def main():
    """
       #     Test mergeSort function
    """

    # List to be sorted
    msObject = MergeSort()
    msObject.array = [10, 7, 3, 9, 3, -5]
    print('Unordered array: {}'.format(msObject.array))

    # Sort list
    mergedArray = msObject.mergeSort()

    # Expected result: [-5, 3, 3,7, 9, 10]
    if mergedArray == [-5, 3, 3, 7, 9, 10]:
        print('Ordered array: {}'.format(mergedArray))
        print("Your Merge Sort Algorithm works !!!")
    def lrs(self, s):
        N = len(s)

        # Form suffix strings
        suffixes = [''] * N
        for i in range(0, N):
            suffixes[i] = s[i:N]

        # Next sort the suffix strings
        sorter = MergeSort()
        sorter.sort_helper(suffixes)

        # Find longest LCP among adjacent entries
        lrs = ''

        for i in range(0, N - 1):
            x = self.lcp(suffixes[i], suffixes[i + 1])

            if len(x) > len(lrs):
                lrs = x

        return lrs
Beispiel #8
0
def main():
    original = [325432, 989, 547510, 3, -93, 189019, 5042, 123,
                597, 42, 7506, 184, 184, 2409, 45, 824,
                4, -2650, 9, 662, 3928, -170, 45358, 395,
                842, 7697, 110, 14, 99, 221]

    numbers = original[:]

    ms = MergeSort(numbers)

    output = ms.sort()

    if is_sorted(output):
        print("** SUCCESS! **")
    else:
        print("Uh oh - not in order.")

    if contain_same_ints(original, numbers):
        print("** Contain the same elements! **")
    else:
        print("Uh oh - something is missing.")

    print(output)
Beispiel #9
0
def main():
    original = [
        325432, 989, 547510, 3, -93, 189019, 5042, 123, 597, 42, 7506, 184,
        184, 2409, 45, 824, 4, -2650, 9, 662, 3928, -170, 45358, 395, 842,
        7697, 110, 14, 99, 221
    ]

    numbers = original[:]

    ms = MergeSort(numbers)

    output = ms.sort()

    if is_sorted(output):
        print("** SUCCESS! **")
    else:
        print("Uh oh - not in order.")

    if contain_same_ints(original, numbers):
        print("** Contain the same elements! **")
    else:
        print("Uh oh - something is missing.")

    print(output)
 def test_merge_sort_empty(self):
     print("Inside test_merge_sort_empty")
     arr = []
     ms = MergeSort()
     sorted_arr = ms.merge_sort(arr)
     self.assertEqual([], sorted_arr)
 def test_merge_sort_two(self):
     print("Inside test_merge_sort_two")
     arr = [6,3]
     ms = MergeSort()
     sorted_arr = ms.merge_sort(arr)
     self.assertEqual([3,6], sorted_arr)
 def test_MergeSort(self):
     self.assertEqual(sorted(self.floatarray), MergeSort(self.floatarray))
Beispiel #13
0
from bubble_sort import BubbleSort
from merge_sort import MergeSort

list_to_sort = [5, 4, 3, 2, 1]
# list_to_sort = [1, 2, 3, 4, 5]
sorting_algo = BubbleSort()
sorting_algo.sort(list_to_sort)

print "Sorted using bubble-sort:"
print list_to_sort

list_to_sort = [5, 3, 4, 2, 1]
sorting_algo = MergeSort()
sorting_algo.sort(list_to_sort)

print "Sorted using merge-sort:"
print list_to_sort
Beispiel #14
0
 def merge_sort(array):
     start = timeit.default_timer()
     copied_array = copy.copy(array)
     MergeSort.sort(array=copied_array)
     end = timeit.default_timer()
     return format(end - start, '.5f')
Beispiel #15
0
 def __init__(self):
     self.graph = CityGraph()
     self.quick_sort = QuickSort()
     self.merge_sort = MergeSort()
Beispiel #16
0
from merge_sort import MergeSort

if __name__ == '__main__':
    # search_tokens = [1, 3, -4, -8, 10]
    search_tokens = [9, 0, 8, 6, 1, 2, 3, 5, 4]
    # search_tokens = ['john', 'anna', 'mark', 'angela', 'james']

    print "ORIGINAL:",
    print search_tokens

    sorter = MergeSort()
    sorter.sort_helper(search_tokens)

    print "SORTED:",
    print search_tokens
 def test_merge_sort(self):
   lst = MergeSort()
   self.assertEqual([1, 1, 2, 3, 4, 5, 6, 7], lst.middle_sort([2, 1, 3, 1, 7, 4, 5, 6]))
 def test_if_method_merges_two_sorted_arrays(self):
     Methods = MergeSort()
     list1 = [1, 2, 1, 11, 6, 5, 7, 10, 5, 4, 3, 5, 6, 11]
     self.assertEqual(Methods.sort(list1),
                      [1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 10, 11, 11])
 def test_merge_sort(self):
     print("Inside test_merge_sort")
     arr = [6,5,3,1,8,7,2,4,4]
     ms = MergeSort()
     sorted_arr = ms.merge_sort(arr)
     self.assertEqual([1,2,3,4,4,5,6,7,8], sorted_arr)
 def test_merge_sort(self):
     sortedList = MergeSort.merge_sort(self.targetList)
     self.assertTrue(sortedList == self.checkList)
Beispiel #21
0
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

# In[3]:

import random
import sys

# ## Generate Data and Sort

# In[24]:

isort = InsertSort([])
msort = MergeSort([])
qsort = QuickSort([])

i_runtime = []
m_runtime = []
q_runtime = []

i_jmptime = []
m_jmptime = []
q_jmptime = []

i_cmprtime = []
m_cmprtime = []
q_cmprtime = []

# In[25]:
Beispiel #22
0
def fn_merge_sort(input, output, start):
    m_sort = MergeSort()
    m_sort.merge_sort(input)
    assert input == output
    end = time.time()
Beispiel #23
0
            dqsort_data = random_data

            # Perform QuickSort on our randomly-generated data
            q_sorting = QuickSort()

            start = time.time()
            q_sorting.quick_sort(qsort_data, 0, len(qsort_data) - 1)
            end = time.time()
            elapsed = end - start

            qsort[array_index] = [
                k, n, q_sorting._compares, q_sorting._shifts, elapsed
            ]

            # Perform MergeSort on our randomly-generated data
            m_sorting = MergeSort()

            start = time.time()
            result = m_sorting.mergesort_asc(merge_data)
            end = time.time()
            elapsed = end - start

            merge[array_index] = [
                k, n, m_sorting._compares, m_sorting._shifts, elapsed
            ]

            # Perform InsertionSort on our randomly-generated data
            i_sorting = InsertionSort()

            start = time.time()
            i_sorting.insertionsort_asc(insert_data)
Beispiel #24
0
from heap_sort import HeapSort
from merge_sort import MergeSort
from quick_sort import QuickSort
from bubble_sort import BubbleSort
from selection_sort import SelectionSort
from insertion_sort import InsertionSort
from time import time

import random

options = {
    1: ("Bubble Sort", BubbleSort()),
    2: ("Selection Sort", SelectionSort()),
    3: ("Insertion Sort", InsertionSort()),
    4: ("Quick Sort", QuickSort()),
    5: ("Merge Sort", MergeSort()),
    6: ("Radix Sort", RadixSort()),
    7: ("Counting Sort", CountingSort()),
    8: ("Heap Sort", HeapSort())
}
print("Sorting Options: ")
for i in options.keys():
    print("Option {} : {}".format(i, options[i][0]))
while True:
    option = int(input("Enter sorting option: "))
    sort_alg = options[option][1]
    start = time()
    arr = [random.randint(-100000, 100000) for _ in range(10)]
    print(arr)
    sort_alg.sort(arr)
    end = time()
Beispiel #25
0
        # repetition for different orders of array size
        for i in range(1,n):    
                
                l = 10**i                                               # order of array size
                arr = [int(random.random()*100) for j in range(l)]      # create an array of random numbers with incremental order
                alist = [0]*len(arr)                                    # initialize an empty array of same size
                times[i-1][0] = l                                       # add the order as the first column in the matrix

                # a loop to go through all the sorting algorithms
                for g in range(1, 6):                                   
                        start = time.clock()                            # get a CPU clock tick
                        if g == 1:
                                temp = SelectionSort.sort(dup(alist, arr))
                        elif g == 2:
                                temp = InsertionSort.sort(dup(alist, arr))
                        elif g == 3:
                                temp = MergeSort.sort(dup(alist, arr))
                        elif g == 4:
                                temp = QuickSort.sort(dup(alist, arr))
                        elif g == 5:
                                temp = CountSort.sort(dup(alist, arr))
                        end = time.clock() - start                       # get a CPU clock tick and estimate algorithm r
                        setin(i, end, g)

endit = time.clock() - begin                                             # estimate overal calculation time
print ('Total time Elapsed:', endit, 'seconds.') 

# show the benchmark matrix
for i in range(0, n-1):
        print (times[i])
 def test_merge_sort(self):
     algo = SortingTestWrapper(MergeSort(), self.n, self.seed)
     self.assertListEqual(algo.integer_sort(), self.verification.integer_sort())