if(sumA<sumB){ int[] temp=a; a=b; b=temp; } int curDiff=1; int oldDiff=Integer.MAX_VALUE; int pA=-1; int pB=-1; boolean shift=true; int len=a.length;//the length of a and b should be the same while(shift&&curDiff>0){ shift=false; curDiff=sum(a)-sum(b); for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ int temp=a[i]-b[j]; int newDiff=Math.abs(curDiff-2*temp); if(newDiff<curDiff&&newDiff<oldDiff){ shift=true; oldDiff=newDiff; pA=i; pB=j; } } } if(shift){ int temp=a[pA]; a[pA]=b[pB]; b[pB]=temp; } } System.out.println("the min diff is "+oldDiff); } public int sum(int[] a){ int sum=0; for(int each:a){ sum+=each; } return sum; } }