Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Booleans 3) Suppose you are given an integer array xs that is sorted in ascending order and you are asked to check whether any pair

Booleans

3) Suppose you are given an integer array xs that is sorted in ascending order and you are asked to check whether any pair of numbers on xs adds up to a number n. One fast way to first check the sum of the smallest and largest numbers, and then

if this sum is correct, the search has succeeded;

if it is too small, the smallest number can be excluded from the search;

if it is too large, the largest number can be excluded.

In the latter two cases, the search continues with the rest of the array. The search fails if/when only one array element remains.

Write the following method that implements this process.

// returns true iff two numbers on xs sum to n

// assumes that xs is sorted in ascending order

public boolean twoSum(int[] xs, int n)

For example, twoSum({1,4,6,8,9}, 12) should return true, and twoSum({1,4,6,8,9}, 11) should return false.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Financial management theory and practice

Authors: Eugene F. Brigham and Michael C. Ehrhardt

12th Edition

978-0030243998, 30243998, 324422695, 978-0324422696

Students also viewed these Programming questions