サーチのアルゴリズム。リニアサーチは配列の前から順番に、見つけたいものを探す。
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <time.h> #define NOT_FOUND (-1) #define N (10) using namespace std; int Linear_search(int x, int *a, int num){ int n = 0; while(n < num && a[n] != x){ n++; } if(n < num){ return n; } return NOT_FOUND; } int main(){ int i, r, array[N]; srand((unsigned int)time(NULL)); cout << "array" << endl; for(i=0;i<N;i++){ array[i] = rand() % 20; cout << "[" << i << "]:" << array[i] << endl; } cout << "Searched Number = "; cin >> i; r = Linear_search(i, array, N); if(r == NOT_FOUND){ cout << i << "is not found" << endl; }else{ cout << i << "is" << r << endl; } }
まず配列の一覧が表示されて
array [0]:13 [1]:10 [2]:0 [3]:13 [4]:15 [5]:18 [6]:15 [7]:19 [8]:14 [9]:7 Searched Number =
探したいものを入力すれば
Searched Number = 11 11 is 6
何番目か教えてくれる。C++の標準ライブラリではfind()関数がリニアサーチに相当。