快速排序和折半查找的代码改自《数据结构(C语言版)》严蔚敏
#include<stdio.h>
int BinarySearch(int *arr, int low, int high, int key)
{
int mid;
while(low <= high)
{
mid = (low + high) / 2;
if(arr[mid] == key) return 1;
else if(arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return 0;
}
int Partition(int *arr, int low, int high)
{
int pivotkey = arr[low];
int temp = arr[low];
while(low < high)
{
while(low < high && arr[high] >= pivotkey) --high;
arr[low] = arr[high];
while(low < high && arr[low] <= pivotkey) ++low;
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
void QSort(int *arr, int low, int high)
{
if(low < high)
{
int pivotloc = Partition(arr, low, high);
QSort(arr, low, pivotloc - 1);
QSort(arr, pivotloc + 1, high);
}
}
int main()
{
int M, N, i, cnt, num;
int arr[4005];
while(scanf("%d%d", &M, &N) != EOF)
{
for(i = cnt = 0; i < M; i++)
{
scanf("%d", &arr[i]);
}
QSort(arr, 0, M-1);
for(i = 0; i < N; i++)
{
scanf("%d", &num);
if(BinarySearch(arr, 0, M-1, num))
cnt++;
}
printf("%d\n", cnt);
}
return 0;
}