I am trying to output different elements from two arrays. So if i have an array A: {9, 0, 1}
and B is {0, 8, 1}
, I need to output an element which included in the first set, but are not included in the second :9
Can not think how I should compare all elements from the first array with the second one.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],b[10],c,n,i,j;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: ",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: ",j+1);
scanf("%d",&b[j]);
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]); }
printf("\n");
for (i = 0; i < n; i++) {
printf("%d ", b[i]); }
printf("\n");
return 0;
}
I'd like to show my thoughts but i think it's stupid:
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[i]!= b[j]){
c=a[i];
}
}
printf("%d ",c);
}
This can be easily solved using Binary search. Follow the simple steps.
Step 1: Sort the second array.
Step 2: For each element of the first array, binary search it in the second array, if its not present , print it, otherwise dont.
The time complexity is O(m log n), where m
is length of first array and n
is length of second array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With