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
Please find the BigO function with explanation for each of the programs below: - Recursive binary...
Please find the BigO function with explanation for each of the programs below: - Recursive binary search - Computing the factorial of N - Computing the N-th Fibonacci number. import java.util.Scanner; public class Recursive { public static void main(String args[]) { int arr[]= {7,9,12,15,28,57,92}; Scanner in = new Scanner(System.in); int key; System.out.print("Enter key to search in array : "); key = in.nextInt(); int index = binarySearch(arr,0,arr.length-1,key); if(index==-1)System.out.println(key + " is not found in array\n"); else System.out.println(key + " is found...
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...
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)...
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,...
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...
Suppose that you want to add items to an array such that the items are always...
Suppose that you want to add items to an array such that the items are always ordered in ascending order; e.g., [1, 2, 2, 4, 5, 8, 9, 14, 32], and any duplicate values are adjacent to each other. We haven’t talked about sorting algorithms yet, so assume you want to be able to keep the items in the array in order without having to sort them. So for example, suppose you want to add the integer value 7 to...
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*...
Write an append function void append(const arrayListType<elemType>& otherList) that will take an array list as a...
Write an append function void append(const arrayListType<elemType>& otherList) that will take an array list as a parameter and append it to the current list. Write an operator+ function that will create a new list containing the contents of the two lists added. arrayListType<elemType> operator+(const arrayListType<elemType> & rhs) const so that you can write code like a = b + c where a b and c are all arrayListTypes. Add your functions to the template and write a main program to...
Language:C++ HAS TO WORK IN VISUAL BASIC I have errors on line 102 "expression must have...
Language:C++ HAS TO WORK IN VISUAL BASIC I have errors on line 102 "expression must have a constant value line 107,108,123,124,127,128: array type int[n] not assignable #include<iostream> #include <fstream> using namespace std; #define size 10000 // Displays the current Inventory Data void Display(int box_nums[],int nboxes[],double ppBox[],int n) // Prints Box number , number of boxes and price per box. { cout<<"Box number Number of boxes in stock Price per box"<<"\n"; cout<<"-------------------------------------------------------------\n"; for(int i=0; i<n; i++) { cout<<box_nums[i]<<" "<<nboxes[i]<<" "<<ppBox[i]<<"\n"; }...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT