Benchmarking sorting algorithms

Assignment Help Other Subject
Reference no: EM133236875

Part 1: Benchmarking Sorting Algorithms

The same task can take vastly different amounts of time, depending on the algorithm that is used to perform the task. You are familiar with simple sorting algorithms such as insertion sort and selection sort. (See Section 7.4 in the textbook.) While these methods work fine for small arrays, for larger arrays they can take an unreasonable amount of time. The question is whether we can do any better.

Java has some built-in sorting methods. They can be found in the class named Arrays in the package java.util. The one that you will use in this lab is Arrays.sort(A), which sorts the entire array A into increasing order. (Actually, there are different methods for different array base types, but all the methods have the same name and are used in the same way. You will be using an array of ints in this lab.)

You should write a program that does the following:

  • Create two arrays of type int[]. Both arrays should be the same size, and the size should be given by a constant in the program so that you can change it easily. 
  • Fill the arrays with random integers. The arrays should have identical contents, with the same random numbers in both arrays. To generate random integers with a wide range of sizes, you could use (int)(Integer.MAX_VALUE * Math.random()). 
  • Sort the first array using either Selection Sort or Insertion Sort. You should add the sorting method to your program; you can copy it from Section 7.4 if you want. (It is a good idea to check that you got the sorting method correct by using it to sort a short array and printing out the result.) 
  • Time how long it takes to sort the array and print out the time. 
  • Now, sort the second (identical) array using Arrays.sort(). Again, time how long it takes, and print out the time.

You should run your program using array sizes of 1,000, 10,000, and 100,000. Record the sort times. Add a comment to the top of the program that reports the times. (You might be interested in applying Arrays.sort() to a million-element array, but don't try that with Selection Sort or Insertion Sort!)

Note: The general method for getting the run time of a code segment is:

long startTime = System.currentTimeMillis();
doSomething();
long runTime = System.currentTimeMillis() - startTime;

This gives the run time in milliseconds. If you want the time in seconds, you can use runTime/1000.0.

Part 2: Programming with Exceptions

In this part of the lab, you will write a program that fetches the information stored at a given URL on the web and saves that data to a file. This will also include networking and file operations and partly an exercise in using exceptions.

For doing I/O, Java has a pair of nice abstractions: InputStream and OutputStream. These are abstract classes in the package java.net. An InputStream is a place from which you can read data; an OutputStream is a place to which you can write data. For this lab, you will use an InputStream to represent the data read from the Web URL, and you will use an OutputStream to represent the file where you want to save a copy of the data. Once you have the streams, the data can be copied just by calling the following method, which you can copy into your program:

private static void copyStream(InputStream in, OutputStream out)
throws IOException {
int oneByte = in.read();
while (oneByte >= 0) { // negative value indicates end-of-stream
out.write(oneByte);
oneByte = in.read();
}
}

Aside from this method, you should have a main routine that does the following:

  • Declare variables to represent the InputStream and the OutputStream. It would be a good idea to initialize them to null to avoid uninitialized variable errors. 
  • Read the URL and the file name as strings from the user. 
  • To connect to the web, you need a variable -- say url -- of type URL (from package java.net). You can create the URL object with the constructor call url = new URL(urlString), where urlString is the string provided by the user. This constructor will throw a MalformedURLException if the string is not a legal URL. (Note: the string must be a complete URL, beginning with "https://".) 
  • To get the input stream, you can simply call url.openStream(), which returns a value of type InputStream. This can throw an IOException, for example, if the web address that you are asking for does not exist. 
  • To get the output stream, you can use the constructor new FileOutputStream(fileName), where fileName is the file name that was input by the user. This can throw a FileNotFoundException if it is not possible to open the specified file for reading (for example, if the user is trying to create a new file in a directory where they don't have write permission). Warning: If a file of the same name already exists, the old file will be erased and replaced by the new one, without giving the user any notice!
  • Now, copy the data from the web into the file by calling the above method. Note that this can throw an IOException.
  • Lasta, use a finally to clause to make sure that both streams are closed (if they were successfully opened). Both InputStream and OutputStream have a close() method for closing the stream. Note that you can test whether the stream was opened by testing whether the value of the variable is still null.

Note that an exception should not crash your program. You should catch the exception and print out a reasonable error message before ending the program. It would be nice if the error message depends on the type of error that occurred (which means using several catch clauses)

Reference no: EM133236875

Questions Cloud

Customer the manufacturer list price : You have purchased a prosperous aircraft repair station from its previous owner, continuing the operation with the same employees. One day in the shop, you obse
Explain the main facts and the court holding : Steven owns a bar, The Lucky Duck. The Lucky Duck employs five bartenders, all of whom he has provided training on mixing drinks and general employment issues.
Civil causes of action in tort : David and Lena had lived in their house in Ermington, Sydney, for 15 years. They have neighbours on both sides and one at the back. Up until now they had had no
Describe applications of data mining in business : MBA 582 Advanced Business Analytics Assignment - University of Alabama at Birmingham - Describe applications of data mining in business
Benchmarking sorting algorithms : The same task can take vastly different amounts of time, depending on the algorithm that is used to perform the task. You are familiar with simple sorting algor
M02-l02-test-driven development : Follow along with the instructor on M02-L02-Test-Driven Development and get the code working for MergeTwoLists on your machine, and add the following test metho
Identify the regional security organization : Identify the regional security organization. Discuss in detail how this regional security organization has a direct or indirect impact on your profession
Disadvantages of bestowing power of assembly : As the geopolitical realities of the world has changed, calls for the reform of the UN Security Council has increased.
What are four model organisms used in scientific research : What are four model organisms used in scientific research? For each, what are two advantages? What are two limitations

Reviews

Write a Review

Other Subject Questions & Answers

  Define piagets concept of object permanence

Define Piaget's concept of object permanence, and describe the connection between object permanence and why is it so important for babies to develop a concept.

  How do you envision the world of seth boardinghouse

Create a director's concept for Joe Turner's Come and Gone using the seven elements outlined in the previous slides: themes, mood/atmosphere, overall look.

  In what ways are the forms of abuse alike

In what ways are these forms of abuse (or violence) alike? Please consider the risk factors, perpetrators, outcomes and the type of abuse.

  Describe how you could convince tim to make necessary change

Describe how you could convince him to make those necessary changes to his lifestyle. Is Tim a good candidate for bypass surgery? Why or why not?

  Models elements from msn program conceptual framework

Discuss using 2-3 models elements from the MSN Program Conceptual Framework to show how you will apply nurse as a Manager of the Healing Environment.

  Discuss and explain the specific methods of that therapy

Discuss and explain the specific methods of that therapy that would be utilized in the treatment of your chosen disorder.

  How the requirements engineering team worked

You will need to describe how the requirements engineering team worked with the clients to perform project requirements discovery or elicitation.

  Identify the research design for the proposed study

Research design. Identify the research design for the proposed study. Choose from case study, ethnography, phenomenology, and grounded theory.

  What does data on juvenile boot camps reveal

What does the data on juvenile boot camps reveal? What are your thoughts on utilizing boot camps as a way of reducing juvenile crime?

  Discussion: pharmacotherapy for respiratory disorders

Discussion: Pharmacotherapy for Respiratory Disorders. Select and research one of the following respiratory disorders: the common cold, pneumonia, or a chronic obstructive pulmonary disease (COPD) such as emphysema or chronic bronchitis

  Who were the key players within each system

After reading the chapters in Tignor, please answer the following questions:

  Briefly describe library, goals, its recent accomplishment

Briefly describe the library, its goals, its recent accomplishments, and the challenges it currently faces. Identify why the JoCo library exists and how it creates value for its stakeholders. Provide examples of how the library balances the needs ..

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd