1.Description
You havencoins (nmay be even or odd) such thatn−1coins are of the same weight and one has different weight. You have a balance scale; you can put any number of coins on each side of the scale at one time, and it will tell you if the two sides weigh the same, or which side is lighter if they do not weigh the same.Outline an algorithm for finding the coin with different weight for each of the following conditions. The number of weighings using your algorithm in each case should beO(logn). You know that one coin weighs more than the others.
2.Algorithm
(1)If the number of coins is even, split them into two parts. If the number is odd, split them into two parts and one coin.
Get the weight of the two parts. The coin which weighs more than other must lie in the part which weighs more.
In the side which weighs more, recursively call step 1. If the weight of two parts are the same, the special coin is the last remaining one.
3.Implementation
public class Coin {
public static void findCoin(int coins[],int left, int right) {
int mid=(int) Math.ceil((left+right)/2); //get the upper limit
int LeftSum=0,RightSum=0;
if(left==right)
{
System.out.println("The special coin is coins["+right+"]");
}
else if(right-left==1)
{
if(coins[left]>coins[right])
{
System.out.println("The special coin is coins["+left+"]");
}
else if(coins[left]>coins[right])
{
System.out.println("The special coin is coins["+right+"]");
}
}
else
{
for(int i=left;iRightSum)
{
right=mid;
findCoin(coins,left,right);
}
else if(LeftSum
Screenshot of the result: