線性搜尋

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"