赞
踩
顺序查找算法也要线性查找算法。该算法针对无序数据,其基本的思想是:从数组的首元素开始,将数组的每个元素逐一与要查找的数据进行比较,直到找到相等的为止,如果查找结束都没有相等的元素,则查找不成功
时间复杂度:O(n)
#include <iostream> using namespace std; template <typename T> // 查找成功返回该元素的index, 失败返回-1 int seq_search(const T seq[], int n, const T &value) { for(int i = 0; i < n; i++) { if(seq[i] == value) { return i; } } return -1; } int main() { int seq[10]={3,7,9,1,4,6,2,8,5,0}; cout << seq_search(seq,10,6) << endl; // 5 cout << seq_search(seq,10,66) << endl; // -1 return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。