您的位置:首页 > 其它

如何在排序数组中,找出给定数字出现的次数

2015-07-27 09:55 435 查看
如何在排序数组中,找出给定数字出现的次数 ? 例如,数组 [1, 2, 2, 2, 3]中2的出现次数为 3

/* 如何在排序数组中,找出给定数字出现的次数 */
int findItemInorderArray(int *arr, int key, int start, int end)
{
	assert(arr);
	assert(start>=0 && end>=0);

	if (start>end) return 0; //该关键字不存在

	static int counter = 0; // 统计关键字key出现的次数
	int index;
	index = (start+end)/2;

	int left,right; //当找到第一个关键字的位置后,从该位置向左(left),向右(right)查找该关键字
					//因为是有序数组,两边一旦遇到不相等的元素,查找终止

	left = right = index;
	if (key == arr[index]) 
	{
		counter++;

		while ((--left) >= start && arr[left]==key)
				counter++;
		while ((++right) <= end && arr[right]==key)
				counter++;
		return counter;
	}
	else if (key > arr[index]) return findItemInorderArray(arr, key, index+1, end);
	else return findItemInorderArray(arr, key, start, index-1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: