#include<iostream> using namespace std; /* 1)先使用快速排序,使得两个数组有序; 2)然后利用二分查找的方法,在数组B中查找; 3)其中,注意在数组B中,使用二分查找的起点,是根据上次查找的结果开确定的;这样可以进一步提高速度; */ int Sort(int array[],int low,int high) { int temp=array[low]; int pos=low; while(low<high) { while(array[high]>temp && high>low)high--; if(high>low)array[low]=array[high]; while(array[low]<temp && high>low)low++; if(low<high)array[high]=array[low]; } array[low]=temp; return low; } void QuickSort(int array[],int low,int high,int len) { if(low<high) { int mid=Sort(array,low,high); QuickSort(array,low,mid-1,len); QuickSort(array,mid+1,high,len); } } int BinarySearch(int array[],int len,int start,int key) { int pos=-1; int low=start; int high=len-1; int mid=0; while(low<=high) { mid=(low+high)/2; if(key>array[mid])low=mid+1; else if(key<array[mid])high=mid-1; else if(key==array[mid]) {pos=mid;break;} } return pos; } void Output(int array_A[],int array_B[],int len_A,int len_B) { QuickSort(array_A,0,len_A-1,len_A); QuickSort(array_B,0,len_B-1,len_B); int i=0,j=0,current=0;//current 记录当前查找的位置; int*array_C =new int [len_A]; int count=0; for(i=0;i<len_A;i++) { j=BinarySearch(array_B,len_B,current,array_A[i]); if(j==-1){continue;} else{ array_C[count]=array_A[i]; count++; current=j+1; } } if(array_C!=NULL) { for(i=0;i<count;i++) { cout<<array_C[i]<<" "; } cout<<endl; } delete []array_C; array_C=NULL; } int main() { int array_A[10]={5,1,7,3,9,0,45,8,12,11}; int array_B[10]={15,1,17,3,23,0,45,33,12,11}; int len_A=10; int len_B=10; Output(array_A,array_B,len_A,len_B); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-15 05:26:15