Пример #1
0
def insertionSortSpec1():
    print('Empty list')
    A0 = list()
    A0_result = insertionSort(A0)
    assert (not bool(A0_result)), "Empty list should return empty list"

    print('\n')
    print('A1 = [5,2,4,6,1,3]')
    A1 = [5, 2, 4, 6, 1, 3]
    A1_result = insertionSort(A1)
    A1_expected = [1, 2, 3, 4, 5, 6]
    assert (A1_result == A1_expected), "A1"

    print('\n')
    print('A2 = [2,1]')
    A2 = [2, 1]
    A2_result = insertionSort(A2)
    A2_expected = [1, 2]
    assert (A2_result == A2_expected), "A2"

    print('\n')
    print('A3 = [0,1,2,3,4,5,6,7]')
    A3 = [0, 1, 2, 3, 4, 5, 6, 7]
    A3_result = insertionSort(A3)
    A3_expected = [0, 1, 2, 3, 4, 5, 6, 7]
    assert (A3_result == A3_expected), "A3"

    print('\n')
    print('A4 = [2]')
    A4 = [2]
    A4_result = insertionSort(A4)
    A4_expected = [2]
    assert (A4_result == A4_expected), "A3"
 def test(self):
     case_a = ['k', 'e', 'p', 'w', 'a', 'n']
     case_b = [5,7,8,1,90,12,0]
     insertionSort(case_a)
     insertionSort(case_b)
     self.assertTrue(['a', 'e', 'k', 'n', 'p', 'w'])
     self.assertTrue([0, 1, 5, 7, 8, 12, 90])
def plotfunction():
    sample_size = 1
    x, y1, y2 = [], [], []

    n = 1000
    for n in range(n, n * 11, n):
        A = random.sample(range(n), n)

        A = insertionSort(A)
        start_time = time.time()
        sorted_A = insertionSort(A)
        end_time = time.time()
        x.append(n)
        y1.append(end_time - start_time)

        A = mergesort(A)
        start_time = time.time()
        sorted_A = mergesort(A)
        end_time = time.time()
        y2.append(end_time - start_time)

    plt.plot(x, y1, label='Insertion')
    plt.plot(x, y2, label='Merge')
    plt.title("Best Case Insertion vs Merge")
    plt.xlabel("Size(N)", color="blue")
    plt.ylabel("Execution Time", color="blue")
    plt.show()
Пример #4
0
def StartAlgorithm():
    global data

    scale = speedScale.get()
    if not data: return

    if algMenu.get() == 'Quick Sort':
        quick_sort(
            data,
            0,
            len(data) - 1,
            drawData,
            scale,
        )

    elif algMenu.get() == 'Bubble Sort':
        bubbleSort(data, drawData, scale)
    elif algMenu.get() == 'Selection Sort':
        selectionSort(data, drawData, scale)
    elif algMenu.get() == 'Merge Sort':
        mergeSort(data, drawData, scale)
    elif algMenu.get() == 'Insertion Sort':
        insertionSort(data, drawData, scale)

    drawData(data, ['green' for x in range(len(data))])
Пример #5
0
 def testSort(self):
     testSorted = [1, 3, 5, 6]
     
     test1 = [1 ,3, 5, 6]
     self.assertEqual(selectionSort(test1), testSorted, 0)
     self.assertEqual(insertionSort(test1), testSorted, 0)
     
     test2 = [1, 3, 6, 5]
     self.assertEqual(selectionSort(test2), testSorted, 0)
     self.assertEqual(insertionSort(test2), testSorted, 0)
     
     test3 = [6, 5, 3, 1]
     self.assertEqual(selectionSort(test3), testSorted, 0)
     self.assertEqual(insertionSort(test3), testSorted, 0)
    def test_insertion_sort(self):

        A = [0, 9, 8, 3, 7, 6]
        sorted_A = [0, 3, 6, 7, 8, 9]

        #Tests for sorting of the list
        self.assertEqual(insertionSort(A), sorted_A)
Пример #7
0
def StartAlgorithm():
    global data
    if not data: return

    if (algMenu.get() == 'Intserion Sort'):
        insertionSort(data, drawData, speedScale.get())

    if (algMenu.get() == 'Bubble Sort'):
        bubble_sort(data, drawData, speedScale.get())

    if (algMenu.get() == 'Selection Sort'):
        selectionSort(data, drawData, speedScale.get())

    if (algMenu.get() == 'Merge Sort'):
        merge_sort(data, drawData, speedScale.get())

    if (algMenu.get() == 'Quick Sort'):
        quick_sort(data, 0, len(data) - 1, drawData, speedScale.get())
        drawData(data, ["green" for x in range(len(data))])
def findMedian(array):
    length = len(array)
    if (length < 6):
        #If the length of the array is smaller than 6, then sort the array and return its median.
        insertionSort(array)
        return array[(length - 1) // 2]
    else:
        nrOfMedians = 0
        medians = []
        #Calculate number of medians.
        if (length % 5 == 0):
            nrOfMedians = length // 5
        else:
            nrOfMedians = length // 5 + 1
        #Split the array in subarrays of maximum 5 elements and add the median.
        for i in range(0, nrOfMedians):
            if (i * 5 + 4 > length):
                insertionSort(array[(i * 5):(length - 1)])
                medians.append(array[(i * 5 + length - 1) // 2])
            else:
                insertionSort(array[(i * 5):(i * 5 + 4)])
                medians.append(array[(10 * i + 4) // 2])
        if (nrOfMedians > 5):
            findMedian(medians)
        return medians[(nrOfMedians - 1) // 2]
Пример #9
0
    def sort(self, type="quick"):
        n = len(self.lst)
        for i in range(self.bucketCount):
            self.bucket.append([])
        for i in range(n):
            self.bucket[math.floor((self.lst[i] - self.min) /
                                   self.bucketSize)].append(self.lst[i])
        m = len(self.bucket)

        for i in range(m):
            k = len(self.bucket[i])
            if k == 1:
                self.result.append(self.bucket[i][0])
                continue
            if k == 0:
                continue
            if type == "quick":
                qs = QuickSort(self.bucket[i])
                qs.quicksort(0, len(self.bucket[i]) - 1)
            elif type == "insert":
                insertionSort(self.bucket[i])
            for j in range(k):
                self.result.append(self.bucket[i][j])
        return self.result
def quicksort_median(array, min, max):
    if max - min >= 10:
        pivot_index = calcMedian(array, min, max)
        array[pivot_index], array[max - 1] = array[max - 1], array[pivot_index]
        pivot_index = max - 1
        l_index = min
        r_index = max - 2
        bool = True
        while bool:
            while array[l_index] <= array[pivot_index] and l_index <= r_index:
                l_index += 1
            while array[r_index] > array[pivot_index] and r_index >= l_index:
                r_index -= 1
            if l_index < r_index:
                array[l_index], array[r_index] = array[r_index], array[l_index]
            else:
                bool = False
        array[l_index], array[pivot_index] = array[pivot_index], array[l_index]
        pivot_index = l_index
        quicksort_median(array, min, l_index - 1)
        quicksort_median(array, l_index + 1, max)
    else:
        array = insertionSort(array, min, max)
    return array
def bucketSort(customList):  #time - O(N^2), SPACE- O(N)
    n_buckets = round(math.sqrt(len(customList)))
    maxValue = max(customList)

    temp_arr = []

    for i in range(n_buckets):
        temp_arr.append([])  #buckets

    for j in customList:
        indexOfBucket = math.ceil(j * n_buckets / maxValue)
        #inserts element in appropriate bucket, starting from 0th index
        temp_arr[indexOfBucket - 1].append(j)

    for i in range(n_buckets):
        temp_arr[i] = insertionSort(temp_arr[i])

    #merge sorted buckets
    k = 0
    for i in range(n_buckets):
        for j in range(len(temp_arr[i])):
            customList[k] = temp_arr[i][j]
            k += 1
    return customList
Пример #12
0
if __name__ == "__main__":
    time_start = time.time()

    nums = RandomArray()
    nums = MergeSort(nums)
    time_end = time.time()
    print('totally cost', time_end - time_start)

    a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    a = MergeSort(a)
    for w in a:
        print(w)

    # for w in nums:
    #     print(w)

    time_start = time.time()

    nums = NearlyOrderArray(swap_times=0, number=50000)
    nums = MergeSort(nums)
    time_end = time.time()
    print('Merge sort totally cost', time_end - time_start)

    time_start = time.time()

    nums = NearlyOrderArray(swap_times=0, number=10000)
    nums = insertionSort(nums)
    time_end = time.time()
    print('Insertion sort totally cost', time_end - time_start)
 def test_already_sorted(self):
     input = [0, 1, 2, 3, 4, 5]
     self.assertEqual(insertionSort(input), sorted(input),
                      "Should be [0,1,2,3,4,5]")
 def test_backwards_array(self):
     input = [5, 4, 3, 2, 1]
     self.assertEqual(insertionSort(input), sorted(input),
                      "Should be [1, 2, 3, 4, 5]")
 def test_unsorted_array(self):
     input = [1, 5, 63, 3, 54, 1]
     self.assertEqual(insertionSort(input), sorted(input),
                      "Should be [1, 1, 3, 5, 54, 63]")
 def test_empty_array(self):
     input = []
     self.assertEqual(insertionSort(input), sorted(input), "Should be []")
     data.append(int(line))
 if sort_fun == 'merge':
     start = time.time()
     mergeSort(data)
     total = time.time() - start
 elif sort_fun == 'quick':
     start = time.time()
     quickSort(data, 0, len(data)-1)
     total = time.time() - start
 elif sort_fun == 'heap':
     start = time.time()
     heapSort(data)
     total = time.time() - start
 elif sort_fun == 'insertion':
     start = time.time()
     insertionSort(data)
     total = time.time() - start
 else:
     print("please input correct method!!!")
 for k in range(0, n-1):
     if data[k] > data[k+1]:
         print("error!")
         break
 print("correct!")
 print("Sorting Time : %dms" % float(1000*total))
 # 開啟檔案
 wb = openpyxl.load_workbook(u'./HW1/學號_HW1_report.xlsx')
 # 設定目前工作的工作表
 ws = wb[sort_fun+' sort result']
 row = dict_n[n] + str(i + 1)
 ws[row] = str(math.floor(1000 * total)) + ' ms'
Пример #18
0
from InsertionSort import insertionSort

assert (insertionSort([]) == [])

assert (insertionSort([3]) == [3])

assert (insertionSort([8, 3]) == [3, 8])

assert (insertionSort([3, 8, 2, 7, 3, 2, 5, 3]) == [2, 2, 3, 3, 3, 5, 7, 8])

assert (insertionSort([3, 8, 5, 6, 7, 1, 2, 9, 2, 3, 7,
                       5]) == [1, 2, 2, 3, 3, 5, 5, 6, 7, 7, 8, 9])
Пример #19
0
def sort(l):
    limit = 30
    if len(l) < 30:
        insertionSort(l)
    else:
        quickSort(l)
from QuickSort_Median import quicksort_median

setrecursionlimit(100000)

n = int(input("Enter the number of elements to be sorted: "))

#Generate random numbers for the given number of elements
content = []
for x in range(n):
    content.append(random.randint(1, int(0.95 * n)))
#Perform insertion sort and take average time by running it thrice
avgTimeArray = []
for x in range(3):
    input1 = copy.deepcopy(content)
    start = time.time()
    result = insertionSort(input1, 0, len(content) - 1)
    end = time.time()
    timeElapsed = end - start
    avgTimeArray.append(timeElapsed)
temp = 0.0
for x in range(3):
    temp += avgTimeArray[x]
avgTime = temp / 3
print("Execution time for Insertion Sort is:", avgTime)

#Perform merge sort and take average time by running it thrice
avgTimeArray = []
for x in range(3):
    input2 = copy.deepcopy(content)
    start = time.time()
    result = mergeSort(input2)
Пример #21
0
from BubbleSort import bubbleSort
from SelectionSort import selectionSort
from InsertionSort import insertionSort

toBeSortedList = [3, 2, 6, 8, 6, 4, 9, 5]
print(f"Unsorted list \n {toBeSortedList}")
sortedList = insertionSort(toBeSortedList)

print(f"Sorted list \n {sortedList}")