基于引用位置的搜索,取决于重新分配内存访问模式的数据元素。
此处,线性搜索方法用于搜索元素。
Begin int find(int *intarray, int n, int item) intialize comparisons = 0 for i = 0 to n-1 Increase comparisons if(item == intarray[i]) Print element with its index break if(i == n-1) Print element not found return -1 Print Total comparisons For j = i till i>0 intarray[j] = intarray[j-1] intarray[0] = item return 0 End
#include<iostream> using namespace std; //执行线性搜索的功能。 //此方法进行线性搜索。 int find(int *intarray, int n, int item) { int i; int comparisons = 0; //浏览所有项目 for(i = 0;i<n;i++) { //计数比较,进行比较++; //如果找到项目,则打破循环 if(item == intarray[i]) { cout<<"元素位于:"<<i<<endl; break; } //如果索引到达末尾,则该项目不存在。 if(i == n-1) { cout<<"\nThe element not found."; return -1; } } printf("Total comparisons made: %d", comparisons); //将每个元素移到匹配项之前。 for(int j = i; j > 0; j--) intarray[j] = intarray[j-1]; //将最近搜索的项目放在数据数组的开头。 intarray[0] = item; return 0; } int main() { int intarray[20]={1,2,3,4,6,7,9,11,12,14,15,16,26,19,33,34,43,45,55,66}; int i,n; char ch; //打印初始数据数组。 cout<<"\nThe array is: "; for(i = 0; i < 20;i++) cout<<intarray[i]<<" "; up: cout<<"\nEnter the Element to be searched: "; cin>>n; //打印更新的数据数组。 if(find(intarray,20, n) != -1) { cout<<"\nThe array after searching is: "; for(i = 0; i <20;i++) cout<<intarray[i]<<" "; } cout<<"\n\nWant to search more.......yes/no(y/n)?"; cin>>ch; if(ch == 'y' || ch == 'Y') goto up; return 0; }
输出结果
The array is: 1 2 3 4 6 7 9 11 12 14 15 16 26 19 33 34 43 45 55 66 Enter the Element to be searched: 26 元素位于:12 Total comparisons made: 13 The array after searching is: 26 1 2 3 4 6 7 9 11 12 14 15 16 19 33 34 43 45 55 66 Want to search more.......yes/no(y/n)?y Enter the Element to be searched: 0 The element not found. Want to search more.......yes/no(y/n)?n