一维最接近点对的分治解法 .

import java.util.Arrays;
import java.util.Scanner;

/*
 * 用分治法输出一个一维数组中的n个不同实数间距离最小的两个实数。输入:实数数组X, 实数个数n, 输出: 距离最小的两个实数.
 * */
public class Divided {

 private static float[] X;
 private static int a = 0;
 private static int b = 0;
 private static float min = Float.MAX_VALUE;

 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt();
  X = new float[n];
  for (int i = 0; i < n; i++) {
   X[i] = sc.nextFloat();
  }
  Arrays.sort(X);
  fun(0, n - 1);
  System.out.println(X[a]);
  System.out.println(X[b]);
 }

 private static void fun(int low, int high) {
  if (low == high) {
   return;
  }
  if (low + 1 == high) {
   if (min > Math.abs(X[high] - X[low])) {
    min = Math.abs(X[high] - X[low]);
    a = low;
    b = high;
   }
  } else {
   int mid = (low + high) / 2;
   fun(low, mid);
   fun(mid + 1, high);
   if (min > Math.abs(X[mid] - X[mid + 1])) {
    min = Math.abs(X[mid] - X[mid + 1]);
    a = mid;
    b = mid + 1;
   }
  }
 }
}

 

 


 

posted @ 2012-01-18 22:58  江海不系舟  阅读(340)  评论(0)    收藏  举报