Question

In: Computer Science

This is on python. 26.1 Lab 6 - Sorting and Runtime Analysis Introduction In this lab,...

This is on python.

26.1 Lab 6 - Sorting and Runtime Analysis

Introduction

In this lab, we will explore sorting algorithms and perform a practical analysis of algorithm runtimes. In lecture, we have introduced algorithm - or asymptotic - analysis. In theoretical analysis, we care about the behavior of our algorithms out at the asymptotes. Or in other words, as the problem sizes get larger and larger, what functions can we use to bound algorithmic runtime? Does an algorithm's runtime grow at a linear rate to the problem size? Or is it logarithmic? Or Quadratic?

From the theoretical perspective, in our discussion of runtime, we care about the number of operations required for algorithms to complete. This allows us to separate the "runtime" of an algorithm from any individual computer on which it is run. Theoretically, we can analyze the runtime of the Merge Sort algorithm irrespective of any specific hardware.

Practically however, we do care about the actual time it takes for algorithms and programs to complete. In this lab, you will perform a runtime analysis to measure the actual time it takes for sorting algorithms selection sort and merge sort to complete for lists of increasing size. Since, on an individual computer, runtime is a good proxy for an algorithm's Big-O behavior, you will illustrate the runtime behaviors of these two algorithms.

This lab is broken into two parts:

  • ZyBooks Coding Portion
  • Canvas Runtime Analysis

Once you complete the coding portion for this lab, you will use it to perform a runtime analysis of both Selection Sort and Merge Sort which you will submit through canvas.

Sort Verification

We will start by writing functions to determine whether lists or files contain sorted data.

A) Warm-up

Write a program that checks whether a list of numbers is sorted in increasing order and prints True if the list is sorted in increasing order, and False otherwise. Test your program for several lists.

B) Is Sorted Function

Refactor your program as a function is-sorted(lst) that takes as input a list of numbers, and returns True if the list is sorted in increasing order, and False otherwise.

Pro-tip: Use doctests to test your function for several inputs.

It’s fantastic if you can make your function recursive, but in this case, it’s ok to use loops as well.

C) Is File Sorted Function

Write a function is_file_sorted(filename). This function takes as input a name of the input file containing a list of integer numbers, one number per line, and returns True if the list is sorted in increasing order, and False otherwise. Test your function with several inputs.

Important: Remember to convert string values to integers before testing. Otherwise your numbers will be sorted alphabetically, for example, numbers [1,2,11,12] will be sorted [1,11,12,2], which is not the right order for integers.

Sort Verifier

Now write a sort_verifier(filename) function that, as above, takes as input a name of the input file containing a list of integer numbers, one number per line, and outputs a user-friendly message with the result, as follows:

>>> sort_verifier("input.txt")
Looks like input.txt needs to be sorted

or

>>> sort_verifier("inputsorted.txt")
Congratulations! The file inputsorted.txt is nicely sorted!

Using Sorting Algorithms

Two sorting algorithms have been provided to you in the file sorters.py. In python, we can import and use functions from other modules (other python source files).

Start with carefully studying the implementations of sorting algorithms provided in sorters.py.

Now add the following line to the top of your lab6.py file:

from sorters import selection_sort, merge_sort

Now you can call on these two functions directly from within lab6.py.

A) Merge Sort Write a function use_mergesort(inputfile, outputfile). This function takes as input a name of the input file containing a list of integer numbers, one number per line, and the output file name. This function should read-in numbers from the file, sort them using the provided merge_sort function, and output the sorted numbers to the output file, one number per line.

Important: Remember to convert string values to integers before testing. Otherwise your numbers will be sorted alphabetically, for example, numbers [1,2,11,12] will be sorted [1,11,12,2], which is not the right order for integers.

B) Selection Sort

Write a function use_selection(inputfile, outputfile). This function takes as input a name of the input file containing a list of integer numbers, one number per line, and the output file name. This function should read-in numbers from the file, sort them using the provided selection_sort function, and output the sorted numbers to the output file, one number per line.

C) Random Number Generator

Then write a function generate_nums(filename, n) that makes a file named filename and writes to it n random numbers from 0 to 99, inclusive. Use generate_nums() function to generate files of different size that you would then use for testing your use_mergesort() and use_selection().

Define this function as follows:

def generate_nums(filename, n):
    import random
    random.seed(0)
    # you fill in the rest

In the above, you are importing the module random and setting the random number generator seed to be 0.

Tip: The instruction

num = random.randrange(0, 10)

will generate a single random number in the range 0-9 inclusive.

Seed Explanation:

In programming there is no such thing as a true random number generator. In reality all algorithmic random number generators are "pseudo-random" number generators. Although there are efforts that go to great lengths to actually import randomness into computing systems.

Algorithmic pseudo-random number generators use complex mathematical functions to approximate random sequences of numbers. While the sequences may seem ransom, they are actually deterministic sequences generated by using a "seed" as the input value to the function. Two "random" sequences generated from the same seed will be identical. In your function, by setting the seed to be 0 you are guarantying that your function called with the same n will always return the same sequence of numbers, a great peroperty for testing and reproducibility purposes. In this application, we don't really care if the numbers are truly random, only that they are not ordered.

Development

You may develop your code in ZyBooks and while in development, you may add code to the bottom of your file outside of the functions for testing purposes. When you go to submit, remove all extraneous code (even a call to main()) as any code outside of the functions may break the ZyBooks tests.

Interactive Terminal

For this lab, an interactive terminal has been enabled for you. This is a beta feature of ZyBooks. In the terminal, you can issue the run command to run your program. You can then directly interact with your program on the terminal, entering user input as needed. You can still opt to run and test your programs the old way, by specifying all input in the "Enter program input" box and clicking on the "Run Program" button.

In the interactive terminal, if you write doctests, you can issue the run -v command to print the output of your doctests.

Solutions

Expert Solution

In this question we have written all the programs using python language as instructed in the question and in this question there is a mention of two major sorting algorithms-

selection sort

this sorting algorithm first finds the minimn of the list and then put it in its perfect position and repeats itself for n number of time so that the final list will be sorted but this algorithm uses brute force approach so its time complexity is high

its time complexity of worstcase senerio is

merge sort

this type if sorting algorithms sort by dividing the list into several small parts and then solving the easy part that is merging them according to the values of elements now because of this properties of the merge sort this algorithm uses divide and conquer approach.

the following are the codes and their outputs

A)CODE:

def sor(test_list):
  key = 0
  i = 1
  while i < len(test_list): 
      if(test_list[i] < test_list[i - 1]): 
          key = 1
      i += 1
        
  # printing result 
  if (not key) : 
      print ("True") 
  else : 
      print ("False") 

OUTPUT:

B)CODE:

def is_sorted(test_list):
  key = 0
  i = 1
  while i < len(test_list): 
      if(test_list[i] < test_list[i - 1]): 
          key = 1
      i += 1
        
  # printing result 
  if (not key) : 
      return True 
  else : 
      return False

OUTPUT:

C)

a)CODE:

def is_file_sorted(file_name):
  with open(file_name,mode='r') as list_file:
    lis=[int(x) for x in list_file.readlines()]
  print(is_sorted(lis))

OUTPUT:

b.)CODE:

def sort_verifier(file_name):
  with open(file_name,mode='r') as list_file:
    lis=[int(x) for x in list_file.readlines()]
  ret=is_sorted(lis)
  if (ret==True):
    print("Congratulations! The file "+file_name+" is nicely sorted!")
  else:
    print("Looks like "+file_name+" needs to be sorted")

OUTPUT:

A)CODE:

def merge(arr, l, m, r): 
    n1 = m - l + 1
    n2 = r- m 
  
    # create temp arrays 
    L = [0] * (n1) 
    rr = [0] * (n2) 
  
    # Copy data to temp arrays L[] and rr[] 
    for i in range(0 , n1): 
        L[i] = arr[l + i] 
  
    for j in range(0 , n2): 
        rr[j] = arr[m + 1 + j] 
  
    # Merge the temp arrays back into arr[l..r] 
    i = 0     # Initial index of first subarray 
    j = 0     # Initial index of second subarray 
    k = l     # Initial index of merged subarray 
  
    while i < n1 and j < n2 : 
        if L[i] <= rr[j]: 
            arr[k] = L[i] 
            i += 1
        else: 
            arr[k] = rr[j] 
            j += 1
        k += 1
  
    # Copy the remaining elements of L[], if there 
    # are any 
    while i < n1: 
        arr[k] = L[i] 
        i += 1
        k += 1
  
    # Copy the remaining elements of R[], if there 
    # are any 
    while j < n2: 
        arr[k] = rr[j] 
        j += 1
        k += 1
  

def mergeSort(arr,l,r): 
    if l < r: 
  
        # Same as (l+r)//2, but avoids overflow for 
        # large l and h 
        m = (l+(r-1))//2
  
        # Sort first and second halves 
        mergeSort(arr, l, m) 
        mergeSort(arr, m+1, r) 
        merge(arr, l, m, r) 
  
  
def use_mergesort(inputfile, outputfile):
  with open(inputfile,mode='r') as list_file:
    lis=[int(x) for x in list_file.readlines()]
  mergeSort(lis,0,len(lis)-1) 
  with open(outputfile,mode='w') as outfile:
    for x in lis:
      outfile.writelines("%d\n"%(x)) 

OUTPUT:

B).CODE:

def selection_sort(A):

  for i in range(len(A)):
    min_= i
    for j in range(i+1, len(A)):
      if A[min_] > A[j]:
        min_ = j
    
   #swap
    A[i], A[min_] = A[min_], A[i]

def use_selection(inputfile, outputfile):
  with open(inputfile,mode='r') as list_file:
    lis=[int(x) for x in list_file.readlines()]
  selection_sort(lis) 
  with open(outputfile,mode='w') as outfile:
    for x in lis:
      outfile.writelines("%d\n"%(x))

OUTPUT:

C.)CODE:

import random
random.seed(0)
def generate_nums(filename, n):
  with open(filename ,'w') as file:
    listt=[]
    for x in range(n):
      listt.append(random.randrange(0, 100))
    for j in listt:
      file.writelines("%d\n"%(j))

OUTPUT:


Related Solutions

In this lab, you will read and write to a file, as well as sorting the...
In this lab, you will read and write to a file, as well as sorting the information. Copy and paste the following into a file named "inputs.txt": 7 199922007 C.J. Cregg Political_Science 200822013 Olivia Dunham Criminal_Justice 199822007 Josh Lyman Law 199922006 Toby Ziegler Communications 200922015 Leslie Knope Public_and_Environmental_Affairs 199922004 Sam Seaborn Law 200722013 Walter Bishop General_Sciences The input file provides details for a student database in the following format: Number_of_students ID_Number Student_First_Name Student_Last_Name Major …… ID_Number Student_First_Name Student_Last_Name Major Your...
26.1 The Application of the compatibility condition in the analysis of statically indeterminate structures is: Necessary...
26.1 The Application of the compatibility condition in the analysis of statically indeterminate structures is: Necessary Sometimes necessary Approximated through the force deformation relation (d) Not related to the above. 26.2 The conditions required to be satisfied for the analysis of statically determinate structures are: Equilibrium only Equilibrium and compatibility Equilibrium, compatibility and force-deformation relation 26.3 The conditions required to be satisfied for the analysis of statically indeterminate structures are: Equilibrium and compatibility only compatibility and force-deformation only force-deformation and...
Lab 1: Measurements and uncertainty estimation Introduction: The purpose of this lab is to measure a...
Lab 1: Measurements and uncertainty estimation Introduction: The purpose of this lab is to measure a quantity related to the static friction of glass. Static friction is the force required to start moving an object from rest. You will place a coin on the glass and lift one end until the coin begins to move. Your goal is to measure the angle at which the coin moves and understand what affects the precision and accuracy of your measurements. 1) Pick...
Runtime complexity of Insertion sort and Mergesort algirthms- and analysis with different size of inputs: In...
Runtime complexity of Insertion sort and Mergesort algirthms- and analysis with different size of inputs: In python Implement a method to sort a given array using the merge sort algorithm. Write a driver program to test the merge sort algorithm and insertion sort algorithm for the arrays of varying lengths provided.. Ex: array lenth 100, Array lenth 1000 etc. Compare the execution time of merge sort with insertion sort. Make sure you use the same array to compare the performance....
Broad crested weir lab report introduction and background.
Broad crested weir lab report introduction and background.
It's time to write a sorting algorithm! In this lab, you'll be writing Bubble Sort. Much...
It's time to write a sorting algorithm! In this lab, you'll be writing Bubble Sort. Much like the previous lab, you will be tasked with prompting the user for a list of values until the user enters 0 (you may use the same initializeVector that you wrote in the last lab). You will then write bubblesort which sorts the vector from smallest to largest. You will then call a function displayVector which displays the vector to the screen. Keep everything...
Implement the following pseudocode in Python Consider the following pseudocode for a sorting algorithm: STOOGESORT(A[0 ......
Implement the following pseudocode in Python Consider the following pseudocode for a sorting algorithm: STOOGESORT(A[0 ... n - 1]) if (n = 2) and A[0] > A[1] swap A[0] and A[1] else if n > 2 m = ceiling(2n/3) STOOGESORT(A[0 ... m - 1]) STOOGESORT(A[n - m ... n - 1]) STOOGESORT(A[0 ... m - 1])
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to...
In Java Please!!! 6.22 LAB: Python and sqlite basics Write a Python program that connects to a sqlite database. Create a table called Horses with the following fields: id (integer): a primary key and not null name (text) breed (text) height (real) birthday (text) Next, insert the following data row into the Horses table: id: 1 name: 'Babe' breed: 'Quarter Horse' height: 15.3 birthday: '2015-02-10' Output all records from the Horses table. Ex: With the above row inserted, the output...
8.40 Lab 8e: BankBalance Introduction For this lab, you will use a do-while loop to complete...
8.40 Lab 8e: BankBalance Introduction For this lab, you will use a do-while loop to complete the task. A do-while loop has this basic structure: /* variable initializations */ do{ /* statements to be performed multiple times */ /* make sure the variable that the stop condition relies on is changed inside the loop. */ } while (/*stop condition*/); Despite the structure of the do-while loop being different than that of a for loop and a while loop, the concept...
Write a long introduction of the lab "flow nets and seepage models"
Write a long introduction of the lab "flow nets and seepage models"
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT