Question

Write a Java program that randomly generates an array of 500,000 integers between 0 and 499,999,...

Write a Java program that randomly generates an array of 500,000 integers between 0 and 499,999, and then prompts the user for a search key value. Estimate the execution time of invoking the linearSearch method in Listing A below. Sort the array and estimate the execution time of invoking the binarySearch method in Listing B below. You can use the following code template to obtain the execution time:

long startTime = System.currentTimeMillis();

perform the task;

long endTime = System.currentTimeMillis();

long executionTime = endTime - startTime;

Here is a sample run:

Enter a search key: 95043⏎

Searching...

The key, 95043, was not found.

Linear search execution time: 11 milliseconds.

Searching...

The key, 95043, was not found.

Binary search execution time: 0 milliseconds.

Must use the following code int he program:

A. Linear Search

public static int linearSearch(int[] list, int key) {

for (int i = 0; i < list.length; i++) {

if (key == list[i])

return i;

}

return -1;

}

B. Binary Search

public static int binarySearch(int[] list, int key) {

int low = 0;

int high = list.length - 1;

while (high >= low) {

int mid = (low + high) / 2;

if (key < list[mid])

high = mid - 1;

else if (key == list[mid])

return mid;

else

low = mid + 1;

}

return –low - 1; // Now high < low, key not found

}

Homework Answers

Answer #1

If you have any doubts, please give me comment...

import java.util.Arrays;

import java.util.Random;

import java.util.Scanner;

public class Searching {

    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);

        Random rndGen = new Random();

        int arr[] = new int[500000];

        for (int i = 0; i < arr.length; i++) {

            arr[i] = rndGen.nextInt(500000);

        }

        System.out.print("Enter a search key: ");

        int search_key = scnr.nextInt();

        long startTime = System.currentTimeMillis();

        System.out.println("Searching...");

        int pos = linearSearch(arr, search_key);

        long endTime = System.currentTimeMillis();

        long executionTime = endTime - startTime;

        if (pos == -1)

            System.out.println("The key, " + search_key + ", was not found");

        else

            System.out.println("The key, " + search_key + ", was found at index " + pos);

        System.out.println("Linear search execution time: " + executionTime + " milliseconds.");

        Arrays.sort(arr);

        startTime = System.currentTimeMillis();

        System.out.println("Searching...");

        pos = binarySearch(arr, search_key);

        endTime = System.currentTimeMillis();

        executionTime = endTime - startTime;

        if (pos < 0)

            System.out.println("The key, " + search_key + ", was not found");

        else

            System.out.println("The key, " + search_key + ", was found at index " + pos);

        System.out.println("Binary search execution time: " + executionTime + " milliseconds.");

    }

    public static int linearSearch(int[] list, int key) {

        for (int i = 0; i < list.length; i++) {

            if (key == list[i])

                return i;

        }

        return -1;

    }

    public static int binarySearch(int[] list, int key) {

        int low = 0;

        int high = list.length - 1;

        while (high >= low) {

            int mid = (low + high) / 2;

            if (key < list[mid])

                high = mid - 1;

            else if (key == list[mid])

                return mid;

            else

                low = mid + 1;

        }

        return -1; // Now high < low, key not found

    }

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Do a trace on the binarySearch method below: variable key holds the value 17, and variable...
Do a trace on the binarySearch method below: variable key holds the value 17, and variable list is a reference to an array with these values {9, 20, 23, 28, 33, 38, 42, 48, 54, 61,73}. public static int binarySearch(int[] list, int key) {     int lowIndex = 0;     int highIndex = list.length - 1;     while (highIndex >= lowIndex) {       int midIndex = (lowIndex + highIndex) / 2;       if (key < list[midIndex]){            highIndex = midIndex...
Write a Java program that asks the user to enter an array of integers in the...
Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 41,...
Build two arrays[ ] (Integer and String) and convert them to two ArrayLists and write two...
Build two arrays[ ] (Integer and String) and convert them to two ArrayLists and write two overloaded generic static search method to find the index locations of a specified value. One of the search methods applies to the array type while the other (overloaded) search method applies to the collection type. Implement the following generic linear search method and write a client program to display results: (Here is the header) public static <E extends Comparable<E>> int search(E[] list, E key)...
Restricted structures such as stack and queue are fast, but they do not support access in...
Restricted structures such as stack and queue are fast, but they do not support access in the key field mode. Group of answer choices True False Big O analysis evaluates an algorithm based on its _________ performance. Group of answer choices A. average-case B. best-case C. worst-case Which of the following algorithms is the fastest in speed? Group of answer choices A. Polynomial time algorithm B. Linear time algorithm C. Exponential time algorithm The following code gives an implementation of...
Hi there, I've been asked to write a program in C which can read values from...
Hi there, I've been asked to write a program in C which can read values from a file then sort them, and then write to a binary file. I'm getting stuck when I write my binary file as the output is just spitting out garbage values and not the values that are being read in. When I print my input file reader everything is perfect but after sorting and then writing, the output is completely wrong. I have checked that...
There is a Java program that is missing one recursive function: public class Fibonacci { /*...
There is a Java program that is missing one recursive function: public class Fibonacci { /* / 0 when n = 0 * fib(n) = | 1 when n = 1 * \ fib(n-1)+fib(n-2) otherwise */ public static int fib(int n) { return 0; } /* Fibonacci Test Framework * * Note, this takes a long time to compute fib(44). */ public static void main(String[] args) { int[] input = { 11, 22, 33, 44}; int[] expect = { 89,...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
Take a look at the file GenericMethods.java. There are three methods you must implement: ·public static...
Take a look at the file GenericMethods.java. There are three methods you must implement: ·public static <T extends Comparable<T>> int findMin(T[] arr): Iterate through the array to find the index of the smallest element in the array. If there are two elements with the smallest value, the method should return the index of the first one. The method should run in O(n). ·public static <T extends Comparable<T>> int findMinRecursive(T[] arr): Should behave just like findMin, but should be implemented recursively....
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT