線性搜尋
December 11, 2021搜尋要有效率,就必須找出資料間的關聯,順序也好、雜湊碼也好,只有完全找不出資料間的任何關聯時,才使用線性搜尋,因為它就只是從資料開頭尋找到最後,看看是否有符合的資料。
解法思路
線性搜尋沒什麼,就是從頭找到尾,例如:
while(i < MAX) {
if(number[i] == k) {
printf("找到指定值");
break;
}
i++;
}
因為線性搜尋沒有效率,只能盡量找一些小地方來試圖改善,像是減少指令數量,例如,將要搜尋的對象放在數列的前方或後方,接著走訪該數列,在程式的撰寫上,只要使用迴圈,省去了 if
判斷,只不過這種改善通常只是聊勝於無。
基本上,如果需要尋找資料,線性搜尋應該要是最後的選項;然而若你的語言,提供了原生的線性搜尋實作,或者搜尋的對象很少,或者不需要重複對同一組對象進行搜尋,在這些特定條件下可以考量線性搜尋,這一方面是因為原生實現或許有速度的優勢,另一方面可能是搜尋前的預處理(例如排序)會有成本;當然,別忘了實際測試效能,看看是否有明顯改善!
程式實作
#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