算法–(在有序和无序数组的分别查找元素)
在无序的数组中查找元素
法一:(循环)
#include<iostream>
using namespace std;
int FinValue1(const int *brr,int n,int val)
{
int pos = -1;
for(int i = 0; i < n; ++i)
{
if(val == brr[i])
{
pos = i;
breaak;
}
}
return pos;
}
法二:(循环)
int FinValue2(const int *brr,int n,int val)
{
int i = n - 1;
while(i >= 0 && brr[i] != val)
{
--i;
}
return i;
}
法三:
int Find(const int *brr,int n,int val)
{
if(n <= 0 || brr[n-1] == val)
{
return n-1;
}
else
{
return Find(brr,n-1,val);
}
}
int FinValue3(const int *brr,int n,int val)
{
if(NULL == brr || n < 1)
return -1;
else
return Find(brr,n,val);
}
int main()
{
int arr[] = {12,34,90,78,67,56,45,100,23};
int n = sizeof(arr) / sizeof(arr[0]);
int val = 45;
int pos = FinValue(arr,n,val);
printf("%d \n",pos);
return 0;
}
在有序数组中查找元素(用二分法)
法一:(循环)
#include<iostream>
using namespace std;
int FindValue(const int *brr,int n,int val)
{
int pos = -1;
int left = 0,right = n-1;
if(NULL == brr || n < 1)
return pos;
while(left <= right)
{
int mid = (right - left + 1) / 2 + left;
if(val < brr[mid])
{
right = mid - 1;
}
else if(val > brr[mid])
{
left = mid + 1;
}
else
{
while(mid < right && brr[mid + 1] == val)
{
++mid;
}
pos = mid;
break;
}
}
return pos;
}
法二:(递归)
int Find(const int *brr,int left,int right,int val)
{
int pos = -1;
if(left <= right)
{
int mi = (right -left + 1) / 2 + left;
if(val < brr[mid])
{
pos = Find(brr,left,mid-1,val);
}
else if(val > brr[mid])
{
pos = Find(brr,mid+1,right,val);
}
else
{
while(pos > left && brr[mid-1] == val)
--mid;
pos = mid;
}
}
return pos;
}
int FindValue(const int *brr,int n,int val)
{
if(NULL == brr || n < 1)
return -1;
else
return Find(brr,0,n-1,val);
}
int main()
{
int arr[] = {12,34,45,56,67,78,89,90,100};
int n = sizeof(arr) / sizeof(arr[0]);
int val = 50;
int pos = FindValue(arr,n,val);
printf("%d \n",pos);
return 0;
}