运行 ❯
获取您
自己的
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
def linearSearch(arr, targetVal): for i in range(len(arr)): if arr[i] == targetVal: return i return -1 arr = [3, 7, 2, 9, 5] targetVal = 9 result = linearSearch(arr, targetVal) if result != -1: print("Value",targetVal,"found at index",result) else: print("Value",targetVal,"not found") #Python
#include <stdio.h> int linearSearch(int arr[], int size, int targetVal); int main() { int arr[] = {3, 7, 2, 9, 5}; int targetVal = 9; int size = sizeof(arr) / sizeof(arr[0]); int result = linearSearch(arr, size, targetVal); if (result != -1) { printf("Value %d found at index %d\n", targetVal, result); } else { printf("Value %d not found\n", targetVal); } return 0; } int linearSearch(int arr[], int size, int targetVal) { for (int i = 0; i < size; i++) { if (arr[i] == targetVal) { return i; } } return -1; } //C
public class Main { public static void main(String[] args) { int[] arr = {3, 7, 2, 9, 5}; int targetVal = 9; int result = linearSearch(arr, targetVal); if (result != -1) { System.out.println("Value " + targetVal + " found at index " + result); } else { System.out.println("Value " + targetVal + " not found"); } } public static int linearSearch(int[] arr, int targetVal) { for (int i = 0; i < arr.length; i++) { if (arr[i] == targetVal) { return i; } } return -1; } } //Java
Python 结果
C 结果
Java 结果
在索引 3 处找到值 9
在索引 3 处找到值 9
在索引 3 处找到值 9