Question: Searching Algorithms [40 points] In Searching class, write a method pairSearch(int [] values, int pairSum) that takes a sorted array and an integer pairSum as

Searching Algorithms [40 points]

In Searching class, write a method pairSearch(int [] values, int pairSum) that takes a sorted array and an integer pairSum as input, returns 1 if it can find two integers in the array whose sum is pairSum and returns -1 if it cannot find a pair of integers whose sum is equal to pairSum.

The pair of integers can be anywhere in the array. They do not have to be consecutive.

The pairSearch method should use linear search algorithm.

Modify the main method in Searching class that prompts users to enter five integer values separated by space and store the integer values in an array. The main method displays the result of the search as well as the number of comparisons the algorithm executes to find the pair of integers (i..e. the value of variable counter).

Sample Run:

Enter five integers: 1 3 4 8 13

Enter sum of two integers: 21

We could find two integers whose sum is 21

The pairSearch method used 24 comparisons to find the pair.

This is the code I have been given:

//******************************************************************** // Searching.java // // Demonstrates the linear and binary search //******************************************************************** public class Searching { public static int counter=0; // counts the number of comparisons // Implementation of linear search public static int linearSearch(int [] numbers, int target) { int i; for (i = 0; i < numbers.length; ++i) { counter ++; if (numbers[i] == target) { return 1; /* found */ } } return -1; /* not found */ } // Implementation of Binary Search public static int binarySearch(int [] numbers, int key) { int mid; int low; int high; low = 0; high = numbers.length - 1;

while (high >= low) { counter ++; mid = (high + low) / 2; if (numbers[mid] < key) { low = mid + 1; } else if (numbers[mid] > key) { high = mid - 1; } else { return 1; // found } }

return -1; // not found } public static void main(String [] args) {

} }

If someone could help that would be great!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!