Question

In: Computer Science

Modify the insertionSort() method in insertSort.java so it counts the number of copies and the number...

Modify the insertionSort() method in insertSort.java so it counts the number of copies and the number of comparisons it makes during a sort and displays the totals. To count comparisons, you will need to break up the double condition in the inner while loop. Use this program to measure the number of copies and comparisons for different amounts of inversely sorted data. Do the results verify O(N2 ) efficiency? Do the same for almost-sorted data (only a few items out of place). What can you deduce about the efficiency of this algorithm for almost-sorted data?

// insertSort.java

class ArrayIns
{
private long[] a; // ref to array a
private int nElems; // number of data items

public ArrayIns(int max) // constructor
{
a = new long[max]; // create the array
nElems = 0; // no items yet
}

public void insert(long value) // put element into array
{
a[nElems] = value; // insert it
nElems++; // increment size
}

public void display() // displays array contents
{
for(int j=0; j<nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}

public void insertionSort()
{
int in, out;

for(out=1; out<nElems; out++) // out is dividing line
{
long temp = a[out]; // remove marked item
in = out; // start shifts at out
while(in>0 && a[in-1] >= temp) // until one is smaller,
{
a[in] = a[in-1]; // shift item to right
--in; // go left one position
}
a[in] = temp; // insert marked item
} // end for
} // end insertionSort()

} // end class ArrayIns

class InsertSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayIns arr; // reference to array
arr = new ArrayIns(maxSize); // create the array

arr.insert(77); // insert 10 items
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

arr.display(); // display items

arr.insertionSort(); // insertion-sort them

arr.display(); // display them again
} // end main()
} // end class InsertSortApp

Solutions

Expert Solution

class ArrayIns
{
private long[] a; // ref to array a
private int nElems; // number of data items

public ArrayIns(int max) // constructor
{
a = new long[max]; // create the array
nElems = 0; // no items yet
}

public void insert(long value) // put element into array
{
a[nElems] = value; // insert it
nElems++; // increment size
}

public void display() // displays array contents
{
for(int j=0; j<nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}

public void insertionSort()
{
int in, out;
int no_of_comparisons=0, no_of_copies=0;

for(out=1; out<nElems; out++) // out is dividing line
{
long temp = a[out]; // remove marked item
in = out; // start shifts at out

boolean already_counted_no_of_comparisons = true; // it will keep track if no of comparisons is incremented by 1
//before the while so that it can't be counted one more time for a single comparisons


no_of_comparisons++; // incrementing number of comparisons

while(in>0 && a[in-1] >= temp ) // until one is smaller,
{
if(already_counted_no_of_comparisons == false){ //checking if already incremented by 1 outside the loop
no_of_comparisons++;
}

a[in] = a[in-1]; // shift item to right
no_of_copies++; // incrementing number of copies
--in; // go left one position
already_counted_no_of_comparisons = false;
}
a[in] = temp; // insert marked item
} // end for

System.out.println("Number of Comparisons : "+ no_of_comparisons);
System.out.println("Number of Copies : "+ no_of_copies);

} // end insertionSort()

} // end class ArrayIns

class InsertSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayIns arr; // reference to array
arr = new ArrayIns(maxSize); // create the array

arr.insert(77); // insert 10 items
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

//2nd Run
// arr.insert(7); // insert 10 items
// arr.insert(2);
// arr.insert(3);
// arr.insert(4);
// arr.insert(5);
// arr.insert(6);
// arr.insert(1);
// arr.insert(8);
// arr.insert(9);
// arr.insert(10);


System.out.println("Before Sorting :");
arr.display(); // display items

arr.insertionSort(); // insertion-sort them

System.out.println("After Sorting :");
arr.display(); // display them again
} // end main()
} // end class InsertSortApp

OUTPUT:

1st Run:

Here, for 10 elements 32 comparisons were done and 31 copies were performed. Complexity is O(n*n).

2nd Run:

  

Since array is almost sorted only 9 comparisons and only one copies were performed.So, complexity in best case is linear i.e. O(n).


Related Solutions

Modify the processFile method so that it will compile and it will not produce a runtime...
Modify the processFile method so that it will compile and it will not produce a runtime error: public static void processFile(File file) { File input = "contents.txt"; String line = null; try { input = new File(file); while ((line = input.readLine()) != null) { System.out.println(line); } return; } finally { if (file != null) { file.close(); } } }
Java - Firstly, write a method, using the following header, that counts the number of prime...
Java - Firstly, write a method, using the following header, that counts the number of prime numbers between from and to (inclusive). public static int countPrimes(int from, int to) For example, countPrimes(11,19) returns 4 since 11, 13, 17 and 19 are primes. You can assume that someone has already written the following function to determine is an integer is prime or not. public static boolean isPrime(int i) // returns true if i is a prime number Secondly, write a program...
Java - Firstly, write a method, using the following header, that counts the number of prime...
Java - Firstly, write a method, using the following header, that counts the number of prime numbers between from and to (inclusive) . public static int countPrimes(int from, int to ) For example, countPrimes(11,19) returns 4 since 11, 13, 17 and 19 are primes. You can assume that someone has already written the following function to determine is an integer is prime or not. public static boolean isPrime(int i) // returns true if i is a prime number Secondly, write...
Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right)...
Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right) element as the pivot, rather than an arbitrary number. (This is similar to what happens in the quickSort1.java program in Listing 7.3.) Make sure your routine will work for arrays of three or fewer elements. To do so, you may need a few extra statements. // partition.java // demonstrates partitioning an array // to run this program: C>java PartitionApp //////////////////////////////////////////////////////////////// class ArrayPar { private...
Java instructions: 1. Modify abstract superclass (Employee10A) so it comment out the abstract payPrint method and...
Java instructions: 1. Modify abstract superclass (Employee10A) so it comment out the abstract payPrint method and uses a toString method to print out it’s instance variables. Make sure toString method cannot be overridden.​​​​​​ Source code below: public abstract class Employee10A {    private String firstName, lastName; static int counter = 0;    public Employee10A(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }    @Override public String toString() { return ("The employee's full name is " + firstName...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method so that it informs the player a mistake has been made, then display the challenge sentence followed by the player’s sentence so the player can determine where the error lies. #-------------------------------------------------------------------------- # # Script Name: TypingChallenge.rb # Version: 1.0 # Author: Jerry Lee Ford, Jr. # Date: March 2010 # # Description: This Ruby script demonstrates how to apply conditional logic # in order...
Modify the following source code so that five subsequent threads print the message “Hello World number,”...
Modify the following source code so that five subsequent threads print the message “Hello World number,” where number indicates the unique thread created; e.g. “Hello World 1” // Your_name_goes_here #include <pthread.h> #include <semaphore.h> sem_t semaphore; // also a global variable just like mutexes void *thread_function( void *arg ) { sem_wait( &semaphore ); // perform some task pthread_exit( NULL ); } int main() { int tmp; tmp = sem_init( &semaphore, 0, 0 ); // initialize pthread_create( &thread[i], NULL, thread_function, NULL );...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when the program runs. Have the program request the number of initial numbers to be entered." //C++ Program 7.14 as follows #include #include #include #include using namespace std; int main() { const int NUMELS = 4; int n[] = {136, 122, 109, 146}; int i; vector partnums(n, n + NUMELS); cout << "\nThe vector initially has the size of " << int(partnums.size()) << ",\n and...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year,...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year, price and rating (G,PG,R…) -Enhance the program so it provides a find by rating function that lists all of the movies that have a specified rating def list(movie_list): if len(movie_list) == 0: print("There are no movies in the list.\n") return else: i = 1 for row in movie_list: print(str(i) + ". " + row[0] + " (" + str(row[1]) + ")") i += 1...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the class's capabilities in a simple program. this is what needs to be modified // Specification file for the FeetInches class #ifndef FEETINCHES_H #define FEETINCHES_H #include <iostream> using namespace std; class FeetInches; // Forward Declaration // Function Prototypes for Overloaded Stream Operators ostream &operator << (ostream &, const FeetInches &); istream &operator >> (istream &, FeetInches &); // The FeetInches class holds distances or measurements...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT