给出2个有序数组,int a[]={1,3,5,7,9},b[]={2,3,4,7,8};怎么找到a[]中每一个元素比b[]中元素大的个数的总数?
法一:
#include<stdio.h>
void getCount(int a[],int n,int b[],int m)
{
int from=0,count=0,k=0;
for(int i=0;i<n;i++)
{
for(int j=from;j<m;j++)
{
if(b[j]<a[i])
{
k++;
from=j+1;
}
else
break;
}
count+=k;
}
printf("the count is:%d\n",count);
}
int main()
{
int a[]={1,3,5,7,9},b[]={2,3,4,7,8};
getCount(a,sizeof(a)/sizeof(int),b,sizeof(b)/sizeof(int));
return 0;
}
法二:
int dominance_count(int f[], int g[], int m, int n)
{
int index_f, index_g;
int count;
count = index_f = index_g = 0;
while (index_f < m && index_g < n)
if (f[index_f] <= g[index_g])
index_f++;
else
index_g++, count += m - index_f;
return count;
}
/* ------------------------------------------------------ */
#include <stdio.h>
void main(void)
{
int x[] = { 1, 2, 4, 7, 9, 12, 13, 15, 16, 20};
int nx = sizeof(x)/sizeof(int);
int y[] = { 4, 5, 7, 8, 9, 10, 11, 13, 16, 19};
int ny = sizeof(y)/sizeof(int);
int dominance_count(int [], int [], int, int), i;
printf("\nDominance Count of two Increasing Arrays\n");
printf("\n # Array 1 Array 2");
printf("\n -- ------- -------");
for (i = 0; i < nx; i++)
printf("\n%3d%10d%10d", i, x[i], y[i]);
printf("\n\nThere are %d Dominance Pairs.",
dominance_count(x, y, nx, ny));
}