Question

In: Computer Science

Based on the source code below, add codes to count how many times array has been...

Based on the source code below, add codes to count how many times array has been access by this program in sorting the array using the insertion sort. Explain how did you count the number of array access on this code. Note that this program tests on 100 until 5000 integers, with increment of 100.

import random

#create randomized array of length 'length' from range 0 up to max
def create_array(length=100, max=5000):
    return [random.randint(0,max) for _ in range(length)]

#executes insertion sort on the input array 'a'
def insertion_sort(a):
   for sort_len in range(1,len(a)):
      cur_item=a[sort_len] #next unsorted item to insert
      insert_idx=sort_len #current index of item

      #iterate down until reach the correct insert spot
      while insert_idx>0 and cur_item<a[insert_idx-1]:
         a[insert_idx]=a[insert_idx-1] #shift elements to make room
         insert_idx+=-1 #decrement the insert spot

        #insert item at correct spot
      a[insert_idx]=cur_item
   return a

#benchmarks the insertion sorting method
from time import time
b0=[] #insertion sort times
n=range(100,5100,100)

for length in n:
    a=create_array(length, length)

    t0 = time()
    s=insertion_sort(a) #sort with insertion sort
    t1=time()
    b0.append(t1-t0) #record insertion time

print("\n|INSERTION SORT|\n")
print("_________________________________________________")
print("n\t\trunning time (s)\t\tNo. of array access") #display number of array access on each n integers in the next column
print("_________________________________________________")
for i,cur_n in enumerate(n):
    print("%d\t\t%f"%(cur_n, b0[i]))

Solutions

Expert Solution

Thanks for A2A.

Below is the changes python code:

import random

#create randomized array of length 'length' from range 0 up to max
def create_array(length=100, max=5000):
    return [random.randint(0,max) for _ in range(length)]

#executes insertion sort on the input array 'a'
def insertion_sort(a):
   count = 0; #to count how many times array is accessed
   for sort_len in range(1,len(a)):
      cur_item=a[sort_len] #next unsorted item to insert
      count += 1 #since above line access the array element
      
      insert_idx=sort_len #current index of item

      #iterate down until reach the correct insert spot

      count += 1 #in while condition cur_item is checked with array element
      #here this count is special one among all other counting in this function
      #as it for while condition false
      while insert_idx>0 and cur_item<a[insert_idx-1]:
         #below count is for while condition true
         count += 1 # since in while cur_item< a[insert_idx-] is true .here alsi accessing a[insert_idx-1]
         
         a[insert_idx]=a[insert_idx-1] #shift elements to make room

         count += 2 # array accessed two times in above line ie, a[insert_idx] ,a[insert_idx-1]
         insert_idx+=-1 #decrement the insert spot

        #insert item at correct spot
      a[insert_idx]=cur_item
      count += 1 # again accessed the array for insert_idx th element in a
   return a,count

#benchmarks the insertion sorting method
from time import time
b0=[] #insertion sort times
arr_access_count = [] #insertion sort array access count
n=range(100,5100,100)

for length in n:
    a=create_array(length, length)

    t0 = time()
    s,count=insertion_sort(a) #sort with insertion sort
    t1=time()
    arr_access_count.append(count)
    b0.append(t1-t0) #record insertion time

print("\n|INSERTION SORT|\n")
print("_________________________________________________")
print("n\t\trunning time (s)\t\tNo. of array access") #display number of array access on each n integers in the next column
print("_________________________________________________")
for i,cur_n in enumerate(n):
    print("%d\t\t%f\t\t\t%d"%(cur_n, b0[i],arr_access_count[i]))

Screenshot of python code:

For better understandablity of special case of couting

consider the a = [1,2,1] and trace the program from sort_len =2.

If you stil have any queries please comment.

Thank you.


Related Solutions

Consider the code below. How many times the value of x is printed? (In other words,...
Consider the code below. How many times the value of x is printed? (In other words, how many times the loop is executed?) public static void main(String args[]) {       int x = 20;       while( x > 10 ) {          System.out.println( x );          x--;       }    } Consider the code below. What needs to be placed instead of ??? so that loop is run exactly 7 times? public static void main(String args[]) {       int x = 7;       while( x > ??? )...
A zip code is a string of five digits (0,1,2,3,4,5,6,7,8,9). How many zip codes are there...
A zip code is a string of five digits (0,1,2,3,4,5,6,7,8,9). How many zip codes are there subject to the following restrictions? (1) Only even digits are allowed. (2) The first digital is even and the last digit is odd (3) Digits cannot be repeated (4) 0 appears exactly four times (5) 0 appears at at least once Solve the following discrete mathematics problem above. Show all work/explanations
1. Adapt the custom array list implementation code with the following changes: (a) Add code to...
1. Adapt the custom array list implementation code with the following changes: (a) Add code to the ensureCapacity() method to print out a message including how many elements are copied to the new array on resizing Array List Implementation: public class MyArrayList<E> implements MyList<E> { public static final int INITIAL_CAPACITY = 16; private E[] data = (E[])new Object[INITIAL_CAPACITY]; private int size = 0; // Number of elements in the list public MyArrayList() { }    public MyArrayList(E[] objects) { for...
write code to count the number of odd integers in an array of 100 random integers...
write code to count the number of odd integers in an array of 100 random integers in the range [0,99].
Description Inversion Count for an array indicates – how far (or close) the array is from...
Description Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j . Example: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). Requirements: • Design...
Inversion Count for an array indicates – how far (or close) the array is from being...
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). What would the complexity of a...
There has been in a push in many communities to source locally. Identify the risks and...
There has been in a push in many communities to source locally. Identify the risks and benefits of sourcing globally versus locally. Please use details and examples when answering this question. Thanks
Are there any statistics that show how many times the Taft-Hartley Act has been actually used...
Are there any statistics that show how many times the Taft-Hartley Act has been actually used to protect workers from their union?
How do i get the code below to add an element before another without making the...
How do i get the code below to add an element before another without making the array off one element? (javascript) public void addBefore(double element) { itemCount++; double data[] = new double[this.data.length]; if(currentIndex <= itemCount) { if(currentIndex != 0) { for(int index = currentIndex; index >= itemCount; index ++) { data[index] = this.data[index]; } currentIndex--; data[currentIndex] = element; } if(currentIndex == 0) { data[0] = element; currentIndex = 0; } } }
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT