The code looks a bit messy and a little complicated! It's not complicated to try it at one pace! Of course, the premise is to understand the idea of the algorithm!
Package Yxd.sf.eightcoins;public class Eightcoins {public static int compareTo (int[] coins, int[] left, int[] right) {int Lefttotal = 0;int Righttotal = 0;int Fakecoin = 0;int coinssize = 0;if (coins.length% 2 = = 0) {coinssize = COINS.LENGTH/2 ;//The current coin is divided into two halves system.arraycopy (coins, 0, left, 0, coinssize);//The first half of the coins are placed leftfor (int i = 0; i < coinssize; i++) {Lefttotal = Lefttotal + left[i]; The total weight of the first half coins is}system.arraycopy (coins, coinssize, right, 0, coinssize);//After half of the coins are placed in rightfor (int j = 0; J < Coinssize; J + +) { Righttotal = Righttotal + right[j];//The total weight of the half coins}}//compare right and left sides of the coin weight if (lefttotal < righttotal && Coinssize ! = 1) {coins = right;int[] right_1 = new int[coinssize/2];int[] Left_1 = new Int[coinssize/2];right = right_1;//dynamically changes array size, minus After treatment, the coin is halved left = left_1; System.arraycopy (coins, 0, left, 0, COINSSIZE/2); System.arraycopy (coins, COINSSIZE/2, right, 0, COINSSIZE/2);} else if (Lefttotal > Righttotal && coinssize! = 1) {coins = left;int[] right_1 = new Int[coinssize/2];int[] Left_1 = new Int[coinssize/2];right = Right_1;left = left_1; System.arraycopy (coins, 0, left, 0, COINSSIZE/2); System.arraycopy (coins, COINSSIZE/2, right, 0, COINSSIZE/2);} if (left.length! = 1 && right.length! = 1 && fakecoin = 0) {fakecoin = CompareTo (coins, left, right); Recursive invocation, if not "fakecoin=" will eventually return to 0}if (left.length = = 1 && right.length = = 1 && coinssize = 2) {if (Left[0] & Lt Right[0]) {fakecoin = right[0],} else if (left[0] = = Right[0]) {System.out.println (left[0] + "and" + Right[0]);} else {fake Coin = Left[0];}} return fakecoin;} public static void Main (string[] args) {int[] coins = {1, 1, 1, 2, 1, 1, 1, 1};int[] left = new int[4];int[] right = new I Nt[4];int flag = 0;int location = compareTo (coins, left, right); for (int i = 0; i < coins.length; i++) {flag++;if (coin S[i] = = location) {System.out.println ("+ Flag +" coin is counterfeit!) ");}}}}
Java implementation--8 coin problem (algorithm)