線形探索 (Linear Search)

forなりforeachなりして順番に要素を取り出し
IDなり名前なりを比較演算するやつ。


C

#include <stdio.h>

int linearSearch(int arr[], int n, int x) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == x) {
            return i;
        }
    }
    return -1;
}

int main() {
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = linearSearch(arr, n, x);
    (result == -1) ? printf("Element not found\n") : printf("Element found at index %d\n", result);
    return 0;
}

C++

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int x) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == x) {
            return i;
        }
    }
    return -1;
}

int main() {
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = linearSearch(arr, n, x);
    (result == -1) ? cout << "Element not found" << endl : cout << "Element found at index " << result << endl;
    return 0;
}

C#

using System;

class Program {
    static int LinearSearch(int[] arr, int x) {
        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] == x) {
                return i;
            }
        }
        return -1;
    }

    static void Main() {
        int[] arr = {2, 3, 4, 10, 40};
        int x = 10;
        int result = LinearSearch(arr, x);
        Console.WriteLine(result == -1 ? "Element not found" : "Element found at index " + result);
    }
}

Java

public class LinearSearch {
    public static int linearSearch(int[] arr, int x) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 10, 40};
        int x = 10;
        int result = linearSearch(arr, x);
        System.out.println(result == -1 ? "Element not found" : "Element found at index " + result);
    }
}

Python

def linear_search(arr, x):
    for i in range(len(arr)):
        if arr[i] == x:
            return i
    return -1

arr = [2, 3, 4, 10, 40]
x = 10
result = linear_search(arr, x)
print("Element found at index" if result != -1 else "Element not found", result)

JavaScript

function linearSearch(arr, x) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === x) {
            return i;
        }
    }
    return -1;
}

const arr = [2, 3, 4, 10, 40];
const x = 10;
const result = linearSearch(arr, x);
console.log(result === -1 ? "Element not found" : "Element found at index " + result);

この記事が気に入ったらサポートをしてみませんか?