Question

Python Merge Sort

Adjust the following code so that you can create random lists of numbers of lengths 10, 15, and 20.

You will run the merge sort 10 times for each length. Record the run time for the length and then calculate the average time to sort.

Finally, compare the average run time for each length to the average time for the Merge Sort.

--------------------------------------------

Initial python code:

import random
import time

def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

mergeSort(lefthalf)
mergeSort(righthalf)

i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1

while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

import random mport tlme def mergeSort(alist) printSplitting ,alist) if len(alist)>l: mid- len(alist)//2 lefthalf - alist:m

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hello, I have something to point out. The lengths 10, 15 or 20 is too low to calculate the run time for this merge sort. The results will always display 0 since the time required to sort lists of these lengths is very minute. To see any notable changes in time, we should use these values multiplied by 100 atleast. So in this program, I have used the lengths 1000, 1500 and 2000 instead of 10,15 and 20. You can change these values as you like, just modify the list called ‘lengths’ as you needed.

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

#code

import random
import time

def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

#defining a list of lengths
lengths=[1000,1500,2000]
#an empty list to store average run times
avg_run_times=[]
#a variable to store total run time
total_run_time=0
#looping through each index in lengths list
for i in range(len(lengths)):
    temp=0 #total run time for current length
    #looping for 10 times
   
for k in range(10):
        #creating a random list containing lengths[i] number of elements
        
aList=[random.randint(0,1000) for j in range(lengths[i])]
        # recording start time
       
start = time.time()
        #sorting
       
mergeSort(aList)
        #recording end time
       
end = time.time()
        #finding elapsed time in seconds
       
elapsed_time = end - start
        #adding to temp
       
temp+=elapsed_time
    #finding average run time for current length
   
avg= temp/10
    #adding to avg_run_times
   
avg_run_times.append(avg)
    #adding temp to total_run_time
  
total_run_time+=temp
   
#finding average time for performing sorting of all lengths
avg_time=total_run_time/(len(lengths)*10)
#displaying heading
print('{:<15s} {:<15s} {:<15s} {:<15s}'.format('Length','Average Time', 'Final Average','Difference'))
#looping and printing length, average time, final average (average taken for all lengths),
#and the difference between average of current length and average as a whole

for i in range(len(lengths)):
    print('{:<15d} {:<15.2f} {:<15.2f} {:<15.2f}'.format(lengths[i], avg_run_times[i], avg_time, avg_run_times[i]-avg_time))

#output

Length 1000 1500 2000 Final Average Difference 0.02 0.02 0.02 Average Time 0.01 0.02 0.03 0.01 0.00 0.01

Add a comment
Know the answer?
Add Answer to:
Python Merge Sort Adjust the following code so that you can create random lists of numbers of lengths 10, 15, and 20. You will run the merge sort 10 times for each length. Record the run time for the...
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
  • In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 pro...

    In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 processes. First half of the array will be sorted by thread 1 and the second half by thread 2. When the threads complete their tasks, the main program will merge the half arrays. You should not waste your time on merge-sort algorithm. Use the merge sort algorithm given below void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j); //right...

  • Consider the following python code that will sort the list of numbers using the Bubble Sort...

    Consider the following python code that will sort the list of numbers using the Bubble Sort algorithm def bubbleSort(alist): print(alist) for j in range (len(alist) - 1, 8, -1): for i in range(): if alist[i] > alist[i + 1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp print(alist) alist = [52, 25, 94, 17, 25, 52] bubbleSort (alist) print(alist) Sort the following series of values into ascending order using the Bubble Sort algorithm. Write out the complete row of...

  • How would I be able to get a Merge Sort to run in this code? MY...

    How would I be able to get a Merge Sort to run in this code? MY CODE: #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include <time.h> using namespace std; class mergersorter { private:    float array[1000] ;    int n = 1000;    int i=0; public:    void fillArray()    {        for(i=1;i<=n;i++)        {            array[i-1]= ( rand() % ( 1000) )+1;        }    }    void arrayout ()    {   ...

  • 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               {                     ...

  • Please give a output Linux/Ubuntu and how to run it (compile) this program ,my assigment is below...

    Please give a output Linux/Ubuntu and how to run it (compile) this program ,my assigment is below : : Merge Sort algorithm using 2 processes a.) Define an integer array of 100 integers. Populate this array with random numbers. You can use int rand(void); function. Do not forget to initialize this function. You will sort the numbers in the array using merge-sort algorithm. In merge sort algorithm the half of the array will be sorted by one process and second...

  • Python 3 5. (16 points) Determine the big-O running time of each of the following functions:...

    Python 3 5. (16 points) Determine the big-O running time of each of the following functions: def pi (a) for i in range(len (a)): print (a[i]) for i in range(len(a)): print (ali]) def p2(a): for i in rangeClen(a)): for j in a: print (ati].j) def p3(a): for i in a: for j in a: print (i,j) def p4(a): for i in range(len(a)): pi(a) def p5(a): for i in range(len(a)): p3 (a) def p6(a): for i in range(len(a)): p5(a) def p7...

  • Implement Merge Sort and test it on a small list of 10 random integer values. c++...

    Implement Merge Sort and test it on a small list of 10 random integer values. c++ please template            // merge-sort S void mergeSort(list& S, const C& less) { typedef typename list::iterator Itor;       // sequence of elements int n = S.size(); if (n <= 1) return;                   // already sorted list S1, S2; Itor p = S.begin(); for (int i = 0; i < n / 2; i++) S1.push_back(*p++);   // copy first half to...

  • 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...

  • Create an ArrayListReview class with one generic type to do the following • Creates an array...

    Create an ArrayListReview class with one generic type to do the following • Creates an array list filled with the generic type of the ArrayListReview class, and inserts new elements into the specified location index-i in the list. (5 points) • Create a method inside the class to implement the calculation of Fibonacci numbers. Use System.nanoTime to find out how much time it takes to get fab(50). Create a method inside the class to check if an array list is...

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
ADVERTISEMENT