标签:
代码如下:
1 public class MergeSort { 2 3 public static void sort(int [] A,int p, int r) 4 { 5 if(p<r) 6 { 7 int q = (int) Math.floor( (p+r)/2 ); 8 sort(A,p,q); 9 sort(A,q+1,r); 10 merge(A,p,q,r); 11 } 12 return ; 13 14 } 15 public static void merge(int [] A, int p, int q, int r) 16 { 17 int n1 = q-p+1; 18 int n2 = r-q; 19 int [] L = new int[n1]; 20 int [] R = new int[n2]; 21 for(int i=0; i<n1; i++) 22 L[i] = A[p+i]; 23 for(int i=0; i<n2;i++) 24 R[i]=A[q+i+1]; 25 26 int i=0; 27 int j=0; 28 int counter = p; 29 while(i<L.length && j<R.length) 30 { 31 if(L[i]<=R[j]) 32 { 33 A[counter]=L[i]; 34 i++; 35 } 36 else 37 { 38 A[counter]=R[j]; 39 j++; 40 } 41 counter++; 42 } 43 if(i==L.length) 44 { 45 for(int k=j;k<R.length;k++) 46 A[counter++] = R[k]; 47 } 48 else 49 { 50 for(int k=i;k<L.length;k++) 51 A[counter++] = L[k]; 52 } 53 } 54 }
1 public class SumTwoEqual { 2 3 /** 4 * @param args 5 */ 6 public static boolean TestExists(int A[],int X) 7 { 8 MergeSort.sort(A, 0, A.length - 1 ); 9 int i = 0; 10 int j = A.length-1; 11 while(i<j) 12 { 13 if(A[i]+A[j]==X) 14 return true; 15 else if(A[i]+A[j] > X) 16 j--; 17 else 18 i++; 19 } 20 return false; 21 } 22 23 public static void main(String[] args) { 24 int A[] = {1,2,5,7,9,14,25,35,13,15}; 25 boolean a = TestExists(A,22); 26 System.out.println(a); 27 } 28 }
算法思想很简单,就是先排序,然后从两边往中间找。
标签:
原文地址:http://www.cnblogs.com/wzm-xu/p/4261233.html