# 線性搜尋

December 11, 2021

## 解法思路

``````while(i < MAX) {
if(number[i] == k) {
printf("找到指定值");
break;
}
i++;
}
``````

## 程式實作

``````#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}

int search(int[]);
int partition(int[], int, int);
void quickSort(int[], int, int);

int main(void) {
srand(time(NULL));

int number[MAX+1] = {0};

int i;
for(i = 1; i <= MAX; i++)
number[i] = rand() % 100;

printf("\n輸入搜尋值：");
scanf("%d", &number[0]);

int find = search(number);
if(find >= 0)
printf("\n找到數值於索引 %d ", find);
else
printf("\n找不到數值");

printf("\n");

return 0;
}

int search(int number[]) {
int i = MAX;
while(number[i] != number[0]) i--;
return i;
}
``````
``````public class Search {
public static int linear(int[] number, int des) {
int[] tmp = new int[number.length + 1];
for(int i = 1; i < tmp.length; i++) {
tmp[i] = number[i-1];
}

tmp[0] = des;

int i = number.length;
while(tmp[i] != tmp[0])
i--;

return i - 1;
}

public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 6, 7, 8};
int find = Search.linear(number, 3);
System.out.println(find >= 0 ? "找到數值於索引" + find : "找不到數值");
}
}
``````
``````def search(number, des):
tmp = [0] * (len(number) + 1)
for i in range(1, len(number)):
tmp[i] = number[i - 1]
tmp[0] = des
i = len(number)
while tmp[i] != tmp[0]:
i -= 1
return i - 1

number = [1, 4, 2, 6, 7, 3, 9, 8]
find = search(number, 2)
print("找到數值於索引 " + str(find) if find >= 0 else "找不到數值")
``````
``````object Search {
def linear(number: Array[Int], des: Int): Int = {
val tmp = new Array[Int](number.length + 1)
for(i <- 1 until tmp.length) {
tmp(i) = number(i - 1)
}
tmp(0) = des
for(i <- number.length until (0, -1) if tmp(i) == des) {
return i -1
}
return -1
}
}

val number = Array(1, 2, 3, 4, 6, 7, 8)
val find = Search.linear(number, 3)
println(if(find >= 0) "找到數值於索引 " + find else "找不到數值")
``````
``````# encoding: UTF-8
def search(number, des)
tmp = Array.new(number.length + 1, 0)
1.upto(number.length  - 1) { |i|
tmp[i] = number[i - 1]
}
tmp[0] = des
i = number.length
while tmp[i] != tmp[0]
i -= 1
end
i - 1
end

number = [1, 4, 2, 6, 7, 3, 9, 8]
find = search(number, 2)
print find >= 0 ? "找到數值於索引 " + find.to_s : "找不到數值", "\n"
``````
``````function search(number, n) {
let i = number.length - 1;
while(i != -1 && number[i] != n) {
i--;
}
return i;
}

let number = [1, 4, 2, 6, 7, 3, 9, 8];
console.log(search(number, 8));
``````
``````linearSearch [] _ = -1
linearSearch lt n = _search lt n 0
where
_search (x:xs) n i =
if x == n then i
else
if xs == [] then -1
else _search xs n (i + 1)

main = print \$ linearSearch [3, 5, 8, 9, 10, 13, 15] 13
``````