不多说,上代码,我的思路是利用快速排序,进行数组排序,而后利用二分查找方法,进行快速定位
int intArray[]={12,451,0,5,45,15,78,23,54,76,451};
void QuickSort(int* a,int low,int high)
{
if(NULL==a)
{
return;
}
if(low>=high)
{
return ;
}
int first=low,last=high;
int key=a[low];
while(first<last)
{
while(first<last&&key<=a[last])
{
last--;
}
a[first]=a[last];
while(first<last&&key>=a[first])
{
first++;
}
a[last]=a[first];
}
a[first]=key;
QuickSort(a,low,first-1);
QuickSort(a,first+1,high);
}
int getFirstPos(int*a,int value,int length)
{
if(NULL==a) return;
int low=0,high=length-1;
int mid=(low+high)/2;
int nPos=-1;
while(low<=high)
{
mid=(low+high)/2;
if(value<a[mid])
{
high=mid-1;
}
else if(value==a[mid])
{
nPos=mid;
high=mid-1;
}
else
{
low=mid+1;
}
}
return nPos;
}
int getLastPos(int*a,int value,int length)
{
if(NULL==a) return;
int low=0,high=length-1;
int mid=(low+high)/2;
int nPos=-1;
while(low<=high)
{
mid=(low+high)/2;
if(value<a[mid])
{
high=mid-1;
}
else if(value==a[mid])
{
nPos=mid;
low=mid+1;
}
else
{
low=mid+1;
}
}
return nPos;
}
int main()
{
QuickSort(intArray,0,10);
cout<<451<<"第一次出现的位置是:"<<getFirstPos(intArray,451,11)<<endl;
cout<<451<<"最后一次出现的位置是:"<<getLastPos(intArray,451,11)<<endl;
}
经测试结果正确