2013-09-02 16:28:35
找出数字在排序数组中出现的次数。
注意几点:
- 一开始试图用size_t类型表示数组的下标begin、end,到那时这样做在end = 0时,end - 1是size_t类型的最大值,仍然满足begin <= end,但此时将会对sortedArray数组中下标为size_t类型的最大值的元素,会出现访问越界;因此,对于数组小标,不要为了保证是整数二用size_t类型,用int类型比较好。
- 若用int型表示,就不需要用STATUS的状态标志,下面的程序中没有修改这一点。
代码:
#include <iostream>
#include <cassert>
using namespace std; typedef int DataType; const bool SuccessToFind = true;
const bool FailToFind = false; bool STATUS = SuccessToFind; //找出第一个K出现的位置的下标
int GetFirstK(DataType *sortedArray,int begin,int end,const DataType data)
{
/*assert(NULL != sortedArray);
assert(begin <= end);*/ STATUS = FailToFind;
int mid = ; while (begin <= end)
{
mid = begin + (end - begin) / ;
if (sortedArray[mid] == data)
{
if (mid == begin || sortedArray[mid - ] != data)
{
STATUS = SuccessToFind;
return mid;
}
else
{
end = mid - ;
}
}
else if (sortedArray[mid] < data)
{
begin = mid + ;
}
else
{
end = mid - ; //mid为0时,若end为size_t类型,会出错
}
} STATUS = FailToFind;
return ;
} //找出最后一个K出现的位置的下标
int GetLastK(DataType *sortedArray,int begin,int end,const DataType data)
{
/*assert(NULL != sortedArray);
assert(begin <= end);*/ STATUS = FailToFind;
int mid = ; while (begin <= end)
{
mid = begin + (end - begin) / ;
if (sortedArray[mid] == data)
{
if (mid == end || sortedArray[mid + ] != data)
{
STATUS = SuccessToFind;
return mid;
}
else
{
begin = mid + ;
}
}
else if (sortedArray[mid] < data)
{
begin = mid + ;
}
else
{
end = mid - ;
}
} STATUS = FailToFind;
return ;
} //返回K出现的次数
int GetNumberOfK(DataType *sortedArray,int len,const DataType data)
{
assert(NULL != sortedArray);
assert(len >= ); size_t begin = GetFirstK(sortedArray,,len - ,data);
size_t end = GetLastK(sortedArray,,len - ,data); if (STATUS == SuccessToFind)
{
return (end - begin + );
}
else
{
return ;
}
} //测试GetNumberOfK
void TestGetNumberOfK()
{
DataType sortedArray[] = {,,,, ,,,, ,};
size_t len = ;
DataType data = ; cout<<"please enter the data to find ,end with ctrl+z "<<endl;
while (cin>>data)
{
cout<<"the number of "<<data<<" in array is : "<<GetNumberOfK(sortedArray,len,data)<<endl;
cout<<"please enter the data to find ,end with ctrl+z "<<endl;
} } int main()
{
TestGetNumberOfK();
return ;
}
测试结果:
please enter the data to find ,end with ctrl+z the number of in array is :
please enter the data to find ,end with ctrl+z the number of in array is :
please enter the data to find ,end with ctrl+z the number of in array is :
please enter the data to find ,end with ctrl+z the number of in array is :
please enter the data to find ,end with ctrl+z
-
the number of - in array is :
please enter the data to find ,end with ctrl+z the number of in array is :
please enter the data to find ,end with ctrl+z
^Z
请按任意键继续. . .