Find common elements of two ordered arrays
1 /*find common elements of two ordered arrays*/2#include <stdio.h>3#include <stdlib.h>4 5 voidFindCommon1 (int*ARR1,int*ARR2,intLen1,intlen2);6 voidFindCommon2 (int*ARR1,int*ARR2,intLen1,intlen2);7 8 9 Ten intMain () One { A intarr1[Ten] = {1,2,3,4,5,6,7,8,9,Ten}; - intarr2[5] = {1,3,5,7,9}; - theFindCommon2 (ARR1,ARR2,Ten,5); - - return 0; - } + - //time complexity of O (len1*len2) + voidFindCommon1 (int*ARR1,int*ARR2,intLen1,intlen2) A { at intI, J; -i = j =0; - while(I < len1 && J <len2) - { - if(Arr1[i] = =Arr2[j]) - { inprintf"%3d", Arr1[i]); -i++; toJ + +; + } - Else theArr1[i] > Arr2[j]? J + +: i++; * } $printf"\ n");Panax Notoginseng } - the //binary lookup of array 2, time complexity O (LEN1*LG (len2)) + voidFindCommon2 (int*ARR1,int*ARR2,intLen1,intlen2) A { the intI, low, mid, high; + for(i =0; i < len1; i++) - { $Low =0; $High = Len2-1; - while(Low <=High ) - { theMID = low + (high-low)/2; - if(Arr1[i] = =Arr2[mid])Wuyi { theprintf"%3d", Arr1[i]); - Break; Wu } - Else AboutArr1[i] < Arr2[mid]? (High = mid-1): (Low = mid +1); $ } -}//end for () -}
Find common elements of two ordered arrays