基本演算法思想-分治演算法
阿新 • • 發佈:2019-01-14
package com.xj.www.algo; import java.util.Scanner; /** * 分治演算法 * * @author xiongjing * */ public class DivideTest { static int FalseCoin(int coin[], int low, int high) { int i, sum1, sum2, sum3; int re = 0; sum1 = sum2 = sum3 = 0; // 演算法具體實現 // 判斷high == 1的情況 if (low + 1 == high) { if (coin[low] < coin[high]) { re = low + 1; return re; } else { re = high + 1; return re; } } // 判斷偶數的情況 if ((high - low + 1) % 2 == 0) { // 將總數分為兩路計算 for (i = low; i <= low + (high - low) / 2; i++) { sum1 += coin[i]; } for (i = low + (high - low) / 2 + 1; i <= high; i++) { sum2 += coin[i]; } if (sum1 > sum2) { re = FalseCoin(coin, low + (high - low) / 2 + 1, high); return re; } else if (sum1 < sum2) { re = FalseCoin(coin, low, low + (high - low) / 2); return re; } else { } } // 判斷奇數的情況 else { for (i = low; i <= low + (high - low) / 2 - 1; i++) { sum1 += coin[i]; } for (i = low + (high - low) / 2 + 1; i <= high; i++) { sum2 += coin[i]; } sum3 = coin[low + (high - low) / 2]; if (sum1 > sum2) { re = FalseCoin(coin, low + (high - low) / 2 + 1, high); return re; } else if (sum1 < sum2) { re = FalseCoin(coin, low, low + (high - low) / 2 - 1); } else { } if (sum1 + sum3 == sum2 + sum3) { re = low + (high - low) / 2 + 1; return re; } } return re; } // 方法主入口 public static void main(String[] args) { int i, n; int weizhi; System.out.println("分治演算法求解假幣問題!"); System.out.print("請輸入硬幣總的個數:"); @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); n = sc.nextInt(); System.out.print("請輸入硬幣的真假:"); int[] coin = new int[n]; for (i = 0; i < n; i++) { coin[i] = sc.nextInt(); } weizhi = FalseCoin(coin, 0, n - 1); System.out.println("在上述" + n + "個硬幣中,第" + weizhi + "個硬幣是假的!"); } }