Question

My tests for sorting algorithms are not working. sorting.py has 6 sorting algorithms and test_sorting.py has...

My tests for sorting algorithms are not working. 
sorting.py has 6 sorting algorithms and test_sorting.py has test cases to run those algorithms, but test cases are not working. 
please correct the errors in test_sorting.py file so that it can test all the sorting algorithms.
 
WARNING: DON'T COPY AND PASTE THE QUESTION IN ANSWER. I WILL REPORT YOU.

sorting.py
# 1. selection sort
# 2. insertion sort
# 3. shell sort
# 4. heap sort
# 5. merge sort
# 6. quick sort
import random
import time
import unittest

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt


class Sorting(object):
    """Sorting class

    """

    def __init__(self):
        self.id = []
        self.size = 0

    def sort_init(self, N):
        '''try:
            self.id = random.sample(range(1, N ** 3), N)
        except ValueError:
            print('Sample size exceeded population size.')'''
        self.id = [random.randint(0, N - 1) for i in range(N)]
        self.size = len(self.id)

    def get_id(self):
        return self.id

    def printArray(self):
        print(self.get_id())

    def selection_sort(self):
        """Selection sort algorithm is an
        in-place comparison sort. It has O(n^2) time complexity, making it
        inefficient on large lists, and generally performs worse than the
        similar insertion sort
        """
        for i_idx, i_item in enumerate(self.id):
            min = i_idx
            for j_idx in range(i_idx + 1, len(self.id)):

                if (self.id[j_idx] < self.id[min]):
                    min = j_idx
            # swap
            temp = self.id[i_idx]
            self.id[i_idx] = self.id[min]
            self.id[min] = temp

    def insertion_sort(self):
        """Insertion sort is a simple sorting algorithm that builds the final
        sorted array (or list) one item at a time. More efficient in practice
        than most other simple quadratic (i.e., O(n^2)) algorithms such as
        selection sort or bubble sort specifically an
        """
        # size is a global variable which contains the length of the array
        size = self.size
        for i in range(1, size):
            temp = self.id[i]
            j = i - 1
            while j >= 0 and temp < self.id[j]:
                self.id[j + 1] = self.id[j]
                j -= 1
            self.id[j + 1] = temp

    def callInsertionSort(self):
        self.insertion_sort()

    def shell_sort(self):
        size = len(self.id)
        gap = size // 2
        while gap > 0:
            for i in range(gap, size):
                temp = self.id[i]
                j = i
                while j >= gap and self.id[j - gap] > temp:
                    self.id[j] = self.id[j - gap]
                    j -= gap
                self.id[j] = temp
            gap //= 2

        return 1

    def callShellSort(self):
        self.shell_sort()

    def heapify(self, arr, n, i):
        largest = i
        left = 2 * i + 1
        right = 2 * i + 2
        if left < n and arr[i] < arr[left]:
            largest = left
        if right < n and arr[largest] < arr[right]:
            largest = right
        if largest != i:  # swap
            arr[i], arr[largest] = arr[largest], arr[i]
            self.heapify(arr, n, largest)  # all the way to bot

    def heap_sort(self, arr):
        n = len(arr)
        for x in range(n - 1, -1, -1):
            self.heapify(arr, n, x)  # heapify from the bottom up
        for x in range(n - 1, -1, -1):
            # swap bot for top, then heapify from 0 passed in for i
            arr[x], arr[0] = arr[0], arr[x]
            self.heapify(arr, x, 0)

    def callHeapSort(self):
        self.heap_sort(self.get_id())

    def merge_sort(self, arr):
        """Merge sort is a divide and conquer algorithm that was invented
        by John von Neumann in 1945. Most implementations produce a stable
        sort, which means that the implementation preserves the input order
        of equal elements in the sorted output.
        """
        if len(arr) > 1:
            mid = len(arr) // 2
            LeftSubArray = arr[:mid]
            RightSubArray = arr[mid:]
            self.merge_sort(LeftSubArray)
            self.merge_sort(RightSubArray)  # now we merge
            i = j = k = 0
            while (i < len(LeftSubArray) and j < len(RightSubArray)):
                if LeftSubArray[i] < RightSubArray[j]:
                    arr[k] = LeftSubArray[i]
                    i += 1
                else:
                    arr[k] = RightSubArray[j]
                    j += 1
                k += 1
            while (i < len(LeftSubArray)):
                arr[k] = LeftSubArray[i]
                k += 1
                i += 1
            while (j < len(RightSubArray)):
                arr[k] = RightSubArray[j]
                k += 1
                j += 1

    def callMergeSort(self):
        self.merge_sort(self.get_id())

    def partition(self, arr, low, high):
        pivot = arr[high]
        i = low - 1
        for j in range(low, high):  # low to high NOT 0,high
            if (arr[j] <= pivot):
                i = i + 1
                arr[i], arr[j] = arr[j], arr[i]
        # now swap the last 2 elements
        arr[i + 1], arr[high] = arr[high], arr[i + 1]
        return i + 1

    def quick_sort(self, arr, low, high):
        if (low < high):  # base case
            part = self.partition(arr, low, high)
            self.quick_sort(arr, low, part - 1)
            self.quick_sort(arr, part + 1, high)

    def callQuickSort(self):
        self.quick_sort(self.id, 0, len(self.id) - 1)

    def shuffleArray(self):
        random.shuffle(self.id)


'''if __name__ == "__main__":
   obj = Sorting()
   obj.sort_init(10)
   obj.printArray()
   obj.callQuickSort()
   obj.printArray()'''

if __name__ == "__main__":  # iteration
    iteration = 0
    obj = Sorting()  # declaring the sorting object
    while iteration < 6:  # change to 6 when including shell
        size_array = [];
        timing = []
        x = 1
        t0 = 0
        temp = []
        degree = 3  # replace to 6 in final
        while x <= degree:  # x goes up to 10^X
            # p0=time.time()
            obj.sort_init(pow(10, x))
            set_szs = [pow(10, x)]  # 10^x, all the way up to 10^6
            t0 = time.time()
            if iteration == 0:
                LineType = "Selection Sort"
                obj.selection_sort()
            elif iteration == 1:
                # Insertion Sort
                LineType = "Insertion Sort"
                obj.callInsertionSort()
            elif iteration == 2:
                # Merge Sort
                LineType = "Shell Sort"
                obj.callShellSort()
            elif iteration == 3:
                # Merge Sort
                LineType = "Merge Sort"
                obj.callMergeSort()
            elif iteration == 4:
                # Heap Sort
                LineType = "Heap Sort"
                obj.callHeapSort()
            elif iteration == 5:
                LineType = "Quick Sort"
                obj.callQuickSort()
            t1 = time.time()
            obj.shuffleArray()
            # t1 = time.time() #Put it back to the top
            total_time = t1 - t0
            print("Iteration", " ", iteration, " ", "Time", LineType, total_time, "DEGREE", x)
            timing.append(total_time)
            size_array.append(set_szs)
            x = x + 1
        iteration = iteration + 1

        plt.plot(size_array, timing, label=LineType)

    # this plots things in log scale (pls google it), you need to add matplotlib to your virtualenv first!

    plt.xscale('log')
    plt.yscale('log')
    plt.legend(loc='upper left')
    plt.xlabel('Number of Objects')
    plt.title('log')
    plt.ylabel('Time')
    plt.show()

test_sorting.py

import unittest
import copy
import sys
sys.path.append('C:/Users/akash/PycharmProjects/student_check/venv/Lib/sorting.py')

class Test_UF(object):
    @classmethod
    def setup_class(klass):
        """This method is run once for each class before any tests are run"""
        print("\n#####  Start Function Tests   #####\n")

    def test_one(self):
        pass

    def test_two(self):
        expected = (1, 2, 3)
        actual = (1, 2, 3)
        assert expected == actual

    def test_single_item(self):
        expected = [1]
        actual = self.sort(expected)
        self.assertEqual(expected, actual)

    def test_two_items_sorted(self):
        expected = [1, 2]
        actual = self.sort(expected)
        self.assertEqual(expected, actual)

    def test_two_items_unsorted(self):
        expected = [2, 1]
        actual = self.sort(expected)
        self.assertEqual(actual, [1, 2])

    def test_zero_in_list(self):
        expected = [10, 0]
        actual = self.sort(expected)
        self.assertEqual(actual, [0, 10])

    def test_odd_number_of_items(self):
        expected = [13, 7, 5]
        actual = self.sort(expected)
        self.assertEqual(actual, [5, 7, 13])

    def test_even_number_of_items(self):
        expected = [23, 7, 13, 5]
        actual = self.sort(expected)
        self.assertEqual(actual, [5, 7, 13, 23])

    def test_duplicate_integers_in_list(self):
        expected = [1, 2, 2, 1, 0, 0, 15, 15]
        actual = self.sort(expected)
        self.assertEqual(actual, [0, 0, 1, 1, 2, 2, 15, 15])

    def test_larger_integers(self):
        expected = [135604, 1000000, 45, 78435, 456219832, 2, 546]
        actual = self.sort(expected)
        self.assertEqual(actual, [2, 45, 546, 78435, 135604, 1000000, 456219832])

    def test_selection_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        # test against built in python sorted() function.
        # expected = sorted(copy.deepcopy(arr_under_test.get_id()))
        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.selection_sort()

        assert expected == actual

    def test_insertion_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.insertion_sort()

        assert expected == actual

    def test_shell_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.shell_sort()

        assert expected == actual

    def test_heap_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.heap_sort()

        assert expected == actual

    def test_merge_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.merge_sort()

        assert expected == actual

    def test_quick_sort_0(self):
        # initialize testbed
        arr_under_test = Sorting()
        arr_under_test.sort_init(10)

        expected = sorted(arr_under_test.get_id())

        actual = arr_under_test.quick_sort()

        assert expected == actual

if __name__== '__main__':
    unittest.main()
0 0
Add a comment Improve this question Transcribed image text
Answer #1
#This program shows an example of selection sort
#Selection sort iterates all the elements and if the smallest element in the list is found then that number
#is swapped with the first
#Best O(n^2); Average O(n^2); Worst O(n^2)
def selectionSort(List):
for i in range(len(List) - 1): #For iterating n - 1 times
minimum = i
for j in range( i + 1, len(List)): # Compare i and i + 1 element
if(List[j] < List[minimum]):
minimum = j
if(minimum != i):
List[i], List[minimum] = List[minimum], List[i]
return List
if __name__ == '__main__':
List = [3, 4, 2, 6, 5, 7, 1, 9]

print('Sorted List:',selectionSort(List))

# Insertion sort is good for collections that are very small
# or nearly sorted. Otherwise it's not a good sorting algorithm:
# it moves data around too much. Each time an insertion is made,
# all elements in a greater position are shifted.
# Best O(n); Average O(n^2); Worst O(n^2)
def insertionSort(List):
for i in range(1, len(List)):
currentNumber = List[i]
for j in range(i - 1, -1, -1):
if List[j] > currentNumber :
List[j], List[j + 1] = List[j + 1], List[j]
else:
List[j + 1] = currentNumber
break
return List
if __name__ == '__main__':
List = [3, 4, 2, 6, 5, 7, 1, 9]

print('Sorted List:',insertionSort(List))

# This program illustrates the shell sort implementation in Python
# According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort.
# It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by
# insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other,
# then progressively reducing the gap between elements to be compared. Starting with far apart elements
# can move some out-of-place elements into position faster than a simple nearest neighbor exchange."
# Best Case O(n logn); Average Case O(depends on gap sequence); Worst Case O(n)
def shellSort(myList):
gap = len(myList) // 2
while gap > 0:
for i in range(gap, len(myList)):
currentItem = myList[i]
j = i
while j >= gap and myList[j - gap] > currentItem:
myList[j] = myList[j - gap]
j -= gap
myList[j] = currentItem
gap //= 2
return myList
if __name__ == '__main__':
myList = [12, 23, 4, 5, 3, 2, 12, 81, 56, 95]

print(shellSort(myList))

# Approach:
# Heap sort happens in two phases. In the first phase, the array
# is transformed into a heap. A heap is a binary tree where
# 1) each node is greater than each of its children
# 2) the tree is perfectly balanced
# 3) all leaves are in the leftmost position available.
# In phase two the heap is continuously reduced to a sorted array:
# 1) while the heap is not empty
# - remove the top of the head into an array
# - fix the heap.
# Time Complexity of Solution:
# Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)).
def HeapSort(alist):
heapify(alist) # create the heap
end = len(alist) - 1
while end > 0:
alist[end], alist[0] = alist[0], alist[end]
shiftDown(alist, 0, end - 1)
end -= 1
def heapify(alist):
''' This function helps to maintain the heap property '''
# start = (len(alist) - 2) // 2 (faster execution)
start = len(alist) // 2
while start >= 0:
shiftDown(alist, start, len(alist) - 1)
start -= 1
def shiftDown(alist, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
# right child exists and is greater than left child
if child + 1 <= end and alist[child] < alist[child + 1]:
child += 1
# if child is greater than root(parent), then swap their positions
if child <= end and alist[root] < alist[child]:
alist[root], alist[child] = alist[child], alist[root]
root = child
else:
return
if __name__ == '__main__':
alist = [12, 2, 4, 5, 2, 3]
HeapSort(alist)

print('Sorted Array:',alist)

#This program gives an example of Merge sort
# Merge sort is a divide and conquer algorithm. In the divide and
# conquer paradigm, a problem is broken into pieces where each piece
# still retains all the properties of the larger problem -- except
# its size. To solve the original problem, each piece is solved
# individually; then the pieces are merged back together.
# Best = Average = Worst = O(nlog(n))
def merge(a,b):
""" Function to merge two arrays """
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c += b
else:
c += a
return c
# Code for merge sort
def mergeSort(x):
""" Function to sort an array using merge sort algorithm """
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = mergeSort(x[:middle])
b = mergeSort(x[middle:])
return merge(a,b)
if __name__ == '__main__':
List = [3, 4, 2, 6, 5, 7, 1, 9]

print('Sorted List:',mergeSort(List))

#This program illustrates an example of quick sort
# Quicksort works by selecting an element called a pivot and splitting
# the array around that pivot such that all the elements in, say, the
# left sub-array are less than pivot and all the elements in the right
# sub-array are greater than pivot. The splitting continues until the
# array can no longer be broken into pieces. That's it. Quicksort is
# done.
# Best = Average = O(nlog(n)); Worst = O(n^2
import time
def quickSort(myList, start, end):
if start < end:
# partition the list
pivot = partition(myList, start, end)
# sort both halves
quickSort(myList, start, pivot-1)
quickSort(myList, pivot+1, end)
return myList
def partition(myList, start, end):
pivot = myList[start]
left = start+1
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
while myList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right
# A more efficient solution
def quicksortBetter(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksortBetter(left) + middle + quicksortBetter(right)
if __name__ == '__main__':
List = [3, 4, 2, 6, 5, 7, 1, 9]
start = time.time()
print('Sorted List:',quickSort(List, 0, len(List) - 1))
stop = time.time()
print('Time Required:', (stop - start))
start = time.time()
print('Sorted List:', quicksortBetter(List))
stop = time.time()

print('Time Required:', (stop - start))

Add a comment
Know the answer?
Add Answer to:
My tests for sorting algorithms are not working. sorting.py has 6 sorting algorithms and test_sorting.py has...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • without coding Give the Big O run-time of the following algorithms. Binary Search: def binary-search (arr,...

    without coding Give the Big O run-time of the following algorithms. Binary Search: def binary-search (arr, low, high, x): # Check base case if low > high : return None else: mid = (high + low) // 2 element arr[mid] == X: if element return mid elif element > X: return binary-search(arr, low, mid 1, x) else: return binary_search(arr, mid + 1, high, x) Selection Sort: def selection_sort (arr): for i in range (len(arr)): smallest index = i smallest value...

  • PLEASE HELP ASAP! in Python, I am supposed to create a program that compares insertion sorting...

    PLEASE HELP ASAP! in Python, I am supposed to create a program that compares insertion sorting and selection sorting. My program only compares insertion and selection once. It is supposed to compare increasing, decreasing and an array of random values for each at 5 different lengths (without looping). Please help me. I have included my code below. import time import random def insertion_sort(arr):     for i in range(1, len(arr)):         key = arr[i]         j = i - 1         while j >= 0...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • the code needs to be modifed. require a output for the code Java Program to Implement...

    the code needs to be modifed. require a output for the code Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...

  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • Student Name Student ID CS209 Data Structures and Algorithms - Quiz 1/2e Friday, Feb 22, 2019...

    Student Name Student ID CS209 Data Structures and Algorithms - Quiz 1/2e Friday, Feb 22, 2019 1. (25 points) Here is an array of five integers: 5,3,4,2,1 Please draw this array after EACH iteration of the large loop (outer loop) in a Bubble sort (sorting smallest to largest). (25 points) Here is an array of five integers: 5,3,4,2,1 Please draw this array after EACH iteration of the large loop (outer loop) in a Selection sort (sortin from smallest to largest)....

  • I need the report like this (idea) *Sorting Algorithms: A sorting algorithm is an algorithm that...

    I need the report like this (idea) *Sorting Algorithms: A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) which require input data to be in sorted lists; it is also often useful for canonical zing data and for producing human-readable output. More formally, the output must satisfy...

  • #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include<time.h> void...

    #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include<time.h> void insertionSort(int arr[], int n); void merge(int a[], int l1, int h1, int h2); void mergeSort(int a[], int l, int h) { int i, len=(h-l+1); //Using insertion sort for small sized array if (len<=5) { insertionSort(a+l, len); return; } pid_t lpid,rpid; lpid = fork(); if(lpid<0) { //Lchild proc not created perror("Left Child Proc. not created\n"); _exit(-1); } else if (lpid==0) { mergeSort(a,l,l+len/2-1); _exit(0); } else...

  • Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace...

    Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void combine(int *a, int low, int high, int mid) {        int i, j, k, c[100000];        i = low;        k = low;        j = mid + 1;        while (i <= mid && j <= high)        {               if (a[i] < a[j])               {                      c[k] = a[i];                      k++;                      i++;               }               else               {                     ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT