# Java exercise using Binary Search ?

This topic is 3166 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am reading from introduction to java 7th edition and I have run into a programming exercise that has me baffled. I understand the code samples in the book but I am completely confused as to what they are trying to get me to do. The program exercise has this description: (Financial application: finding the sales amount) Rewrite Listing 4.9, FindSalesAmount.java using the binary search approach. Since the sales amount is between 1 and COMMISSION_SOUGHT / 0.08, you can use a binary search to improve it. Here is there Listing 4.9
public class FindSalesAmount {
/** Main method */
public static void main(String[] args) {
// The commission sought
final double COMMISSION_SOUGHT = 25000;
final double INITIAL_SALES_AMOUNT = 0.01;
double commission = 0;
double salesAmount = INITIAL_SALES_AMOUNT;

do {
// Increase salesAmount by 1 cent
salesAmount += 0.01;

// Compute the commission from the current salesAmount;
if (salesAmount >= 10000.01)
commission =
5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;
else if (salesAmount >= 5000.01)
commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;
else
commission = salesAmount * 0.08;
} while (commission < COMMISSION_SOUGHT);

// Display the sales amount
System.out.println(
"The sales amount $" + (int)(salesAmount * 100) / 100.0 + "\nis needed to make a commission of$" + COMMISSION_SOUGHT);
}
}


Here is there binarySearch:
public class BinarySearch {
/** Use binary search to find the key in the list */
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
}
}


What are they trying to get me to do with binary search and FindSalesAmount? I understand both programs seperately however I have no clue as to how they can be combined int one program as in the problem description. Any help is greatly appreciated. Thanks!

##### Share on other sites
I don't think they're asking you to use the actual BinarySearch class; they just want you to use the algorithm.

Do you see that do..while loop in FindSalesAmount? It's an incremental search. It checks salesAmount = 0.02, then salesAmount = 0.03, then salesAmount = 0.04, and so on, until it finds the right commission. What they're saying is that you should try a different search strategy - a binary search - checking different values of salesAmount so that you find the result more quickly.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 9
• 11
• 9
• 9
• ### Forum Statistics

• Total Topics
633714
• Total Posts
3013493
×