Question

In: Computer Science

Compare the performance between linearSearch, BinarySearch, InsertOrdered and InsertNotOrdered using System.nanoTime(); Fill the following table          ...

  1. Compare the performance between linearSearch, BinarySearch, InsertOrdered and InsertNotOrdered using System.nanoTime();

Fill the following table

         

Method

N= 100

N = 1000

N = 100000

N=1000000

InsertOrdered

Insert

LinearSearch(find method in HighArray)

BinarySearch

Here is a sample code to read data from file

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class FileReaderSample {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner in = new Scanner(System.in);

        System.out.println("Please enter file name");

      String s = in.nextLine();

        Scanner input = new Scanner(new File(s));

        int[] arr = new int[100];

        int i = 0;

        while (input.hasNextInt()) {

            int next = input.nextInt();

            arr[i] = next;

            i++;

        }// end while

        int nElems = i;

// Print the array contents

       System.out.println("Array Contents");

        for (i = 0; i < nElems; i++) {

            System.out.println(i + "\t" + arr[i]);

        }// end for

    }// end main

}// end class

Solutions

Expert Solution

Working code implemented in Java and appropriate comments provided for better understanding.

Source Code for ArrayListVoteCounter.java:

package votecounterproject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;

public class ArrayListVoteCounter {

private ArrayList<String> votes;
private ArrayList<String> spoiledVotes;
private SithSenateMember[] sithSenateMembers;
  
// TODO: Remove the index trackers.
private int voteIndex;
private int spoiledVoteIndex;

/**
* Create new ArrayVoteCounter with file
* Collect election data
*/
public ArrayListVoteCounter() {
votes = new ArrayList<>();
spoiledVotes = new ArrayList<>();
sithSenateMembers = new SithSenateMember[4];
  
// TODO: Remove the index trackers.
voteIndex = 0;
spoiledVoteIndex = 0;
  
  
setupCandidates();
}

/**
* Initialize 4 Sith Senate Members into the sithSenateMembers array
*/
private void setupCandidates() {
sithSenateMembers[0] = new SithSenateMember("Sidius");
sithSenateMembers[1] = new SithSenateMember("Maul");
sithSenateMembers[2] = new SithSenateMember("Vader");
sithSenateMembers[3] = new SithSenateMember("Plagueis");
}

/**
* Add each vote to votes array
* @param name the full name of the sith senate member
*/
public void recordVote(String name) {
if (!name.isEmpty()) {

voteIndex++;

switch (name) {
case "Darth Sidius":
sithSenateMembers[0].addVote();
break;
case "Darth Maul":
sithSenateMembers[1].addVote();
break;
case "Darth Vader":
sithSenateMembers[2].addVote();
break;
case "Darth Plagueis":
sithSenateMembers[3].addVote();
break;
default:

spoiledVoteIndex++;
}
}
}

/**
* Display results
* Show percent of votes earned by each candidate
*/
public void reportResults() {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(1);
int validVotes = votes.size() - spoiledVotes.size();
System.out.println(validVotes + " valid votes were cast.");
for (SithSenateMember sithSenateMember : sithSenateMembers) {
System.out.println("Darth " + sithSenateMember.getSurname() + ": " + getSithSenateMemberVotes(sithSenateMember.getFullName())
+ " votes, " + df.format(sithSenateMember.getNumVotes() / (float) validVotes * 100)
+ "%.");
}
System.out.println("There were " + spoiledVotes.size() + " spoiled votes.");
}

/**
* TODO Remove the whole function since ArrayList auto-expands its container length
* Copy contents of array into a new one of double the original length
* @param myArray to be expanded
* @return new array
*/
private String[] expandCapacity(String[] myArray) {
String[] newArray = Arrays.copyOf(myArray, myArray.length * 2);
return newArray;

}

/**
* Method used for testing
* @param name - the senate member's name
* @return the number of votes for the candidate.
*/
public int getSithSenateMemberVotes(String name) {
for (int i = 0; i < sithSenateMembers.length; i++) {
if(sithSenateMembers[i].getFullName().equalsIgnoreCase(name) ||
sithSenateMembers[i].getSurname().equalsIgnoreCase(name))
return sithSenateMembers[i].getNumVotes();
}
return 0;
}
  
/**
* Getter
*
* @return the votes array list
*/
public ArrayList<String> getVotes() {
return votes;
}

/**
* Getter
*
* @return the spoiled votes array list
*/
public ArrayList<String> getSpoiledVotes() {
return spoiledVotes;
}

/**
* Begin Random Test Zone
*/
  
/**
* Builds and runs a random array vote counter object.
*/
public static void runRandomElectionResults() {
ArrayListVoteCounter voteCounter = new ArrayListVoteCounter();
voteCounter.setupCandidates();
voteCounter.generateRandomElectionData();
voteCounter.reportResults();
}

/**
* Generate random election data after shuffling the candidate array contents.
* Generates decent variation among the candidates.
*/
private void generateRandomElectionData() {
int n;
int ballotCount = ThreadLocalRandom.current().nextInt(99999);
Collections.shuffle(Arrays.asList(sithSenateMembers));
for (int i = 0; i < ballotCount; i++) {
n = ThreadLocalRandom.current().nextInt(0, 100);
if(0 < n && n < 25)
recordVote(sithSenateMembers[0].getFullName());
else if(25 < n && n < 45)
recordVote(sithSenateMembers[1].getFullName());
else if(45 < n && n < 74)
recordVote(sithSenateMembers[2].getFullName());
else if(74 < n && n < 95)
recordVote(sithSenateMembers[3].getFullName());
else
recordVote("unknown");
}
}
  
}


Related Solutions

Fill in the blanks on the following table
 Fill in the blanks on the following tableE&pshareholder basisdistributiondividendreturn of capitalcapital gain20,000300,00080,000120,00010,000170,000220,000100,000170,00020,000080,000<20,000>50,000170,000
Using the mtcars dataset, answer the following questions: Fill in the following table: Variable Correlation with...
Using the mtcars dataset, answer the following questions: Fill in the following table: Variable Correlation with mpg cyl -0.85216 disp -0.84755 hp -0.77617 drat 0.681172 wt -0.86766 qsec 0.418684 vs 0.664039 am 0.599832 gear 0.480285 carb -0.55093 mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21 6 160 110 3.9 2.62 16.46 0 1 4 4 Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108...
Fill in the blanks in the following table using the Porphyry Copper Deposit description as an example.
Fill in the blanks in the following table using the Porphyry Copper Deposit description as an example. To enter data, just click on the cell and start typing. The cell will stretch to fit your answer. question is from introduction to mining 1MI1033 - Introduction to MiningModule #1, Unit #2 – Resources and Ore Deposit FormationDeposit TypePrincipal Ore Mineral(s)Secondary Ore Mineral(s)Name An Example of a Deposit and its LocationGrade And Tonnage Characterization DescriptionTypical Mining MethodsSize or Dimension of the DepositShape of...
Answer the following questions or fill in the blanks using information contained in the periodic table....
Answer the following questions or fill in the blanks using information contained in the periodic table. a) Boron has properties of both metals and nonmetals and is called a _____________. b) Transition metals are also known as _____-block elements when writing electron configurations. c) Certain nonmental elements like to exist as a pair (H2, F2, etc...) and are called _____________. d) Rows in the periodic table are called _____________. e) Group 18 elements are better known as_______________. f) Iced tea...
Fill in the blanks to complete the following table.
Fill in the blanks to complete the following table.SymbolIon FormedNumber of Electrons in IonNumber of Protons in IonF__________9Te_____54_____II−_______________Mg2+_____12Part AComplete the first column of the table.Express your answer as a chemical symbol.Part BComplete the second column of the table.Express your answer as ions. Enter your answers in order given in the table, from top to bottom, separated by a comma.Part CComplete the third column of the table.Express your answer as integers. Enter your answers in order given in the table, from...
Fill in the table and answer the following questions
Fill in the table and answer the following questions **** (Use D-method) Class Frequency 10 – 12 6 13 – 15 4 16 – 18 14 19 – 21 15 22 – 24 8 25 – 27 2 28 – 30 1   50 Class Real limits f cf x d fd     10 – 12                 13 – 15                 16 – 18  ...
Using this table, please fill the table, draw the stress strain curve and then answer the...
Using this table, please fill the table, draw the stress strain curve and then answer the question. In case where the load is released at point 1 and 2 Draw and show the permanent and the recovery deformations. 0 1 2 3 Force 0 Kn 400 Kn 650 Kn 550 Kn Length 2 cm 2.004 cm 2.036 cm 2.049 cm Diameter 1 cm 0.9995 cm 0.998 cm 0.996 cm ∆L/L ∆d/d ᵋx ᵋz Calculate the Yield stress in the wire...
Fill-in the blanks of the following table and answer the following questions.
Fill-in the blanks of the following table and answer the following questions.                                Year                         Nominal GDP $                Real GDP $                      GDP Deflator       20052,000, 0002,000,000_____________20062,310,000___________         105Find the GDP Deflator in year 2005.Find the Real GDP in year 2006.Which GPD matters, nominal or real GDP? Why?Did the economy grow in year 2006? Why yes, why not?
Fill in the table using the following information. Assets required for operation: $4,000 Case A—firm uses...
Fill in the table using the following information. Assets required for operation: $4,000 Case A—firm uses only equity financing Case B—firm uses 30% debt with an 8% interest rate and 70% equity Case C—firm uses 50% debt with a 12% interest rate and 50% equity What happens to the return on the stockholders’ equity as the amount of debt increases? Why did the rate of interest increase in case C?
Using the following data... (a) Fill in the table: X Y X2 Y2 XY 8 5...
Using the following data... (a) Fill in the table: X Y X2 Y2 XY 8 5 4 3 9 7 7 6 5 6 ΣX = ΣY = ΣX2 = ΣY2 = ΣXY = (b) Compute the degrees of freedom and determine the critical value of r for α = 0.05 (two-tails). df = r-critical =   (c) Compute SSX, SSY, SP, and the Pearson correlation (r). (Use 3 decimals) SSX = SSY = SP = r = (d) What decision...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT