/**
* 输出数组a中不在数组b中出现的元素
* @author xqh
*
*/
public class ArrayFindNum {
public static void main(String[] args) {
int[] a = { 1, 3, 0, 4, 2 }; //数组a
int[] b = { 1, 2, 3, 4, 5 }; //数组b
List<Integer> list = new ArrayList<Integer>(); //数列
Arrays.sort(b); //对数组b排序
for (int i = 0; i < a.length; i++) {
if (!binarySearch(b, a[i])) // 采用二分查找法判断数组a中的元素是否出于在数组b中
list.add(a[i]); // 数列存放不出现在数组b中的元素
}
System.out.println("数组a中不在数组b中出现的元素:");
for (int i : list)
System.out.print(i + " ");
}
/**
* 二分查找法
* @param arr 数组
* @param num 数值
* @return 找到则返回true,否则返回false
*/
private static boolean binarySearch(int[] arr, int num) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (arr[middle] == num) {
return true;
} else if (arr[middle] > num) {
high = middle - 1;
} else
low = middle + 1;
}
return false;
}
}
http://topic.csdn.net/u/20110509/19/d837e340-58d7-4c04-a1c9-641ec432ce8f.html