Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

หาค่าต่ำสุดในอาร์เรย์ด้วย Linear Search ในภาษา C

Linear Search: ค้นหาแบบบลำดับ (Sequential Search)

ตรวจสอบทีละสมาชิกจากต้นจนจบ ไม่ต้องเรียงลำดับก่อน แต่อ่อนกว่า Binary Search สำหรับข้อมูลมาก

โปรแกรม 1: ค้นหา Key ด้วย Linear Search

#include <stdio.h>

int main() {
    int a[50], n, i, key, flag = 0;
    printf("enter the no: of elements");
    scanf("%d", &n);
    printf("enter the elements:");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    printf("enter a key element:");
    scanf("%d", &key);
    for (i = 0; i < n; i++) {
        if (a[i] == key) {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
        printf("search is successful:");
    else
        printf("search is unsuccessfull:");
    return 0;
}

โปรแกรม 2: หาค่าต่ำสุด (Minimum) ด้วย Linear Search

#include <stdio.h>

int min_ele(int numbers[], int n) {
    int min = numbers[0];
    int i;
    for (i = 1; i <= n; i++) { // หมายเหตุ: ควรเป็น i < n
        if (min > numbers[i])
            min = numbers[i];
    }
    return min;
}

int main() {
    int n;
    printf("Enter no: of elements in an array: ");
    scanf("%d", &n);
    int numbers[n];
    int i, min;
    printf("Enter %d numbers : ", n);
    printf("\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }
    min = min_ele(numbers, n);
    printf("\nIn an array the minimum number is: %d\n", min);
    return 0;
}

ตัวอย่าง Output โปรแกรม 2

Enter no: of elements in an array: 5
Enter 5 numbers:
23 56 78 9 20
In an array the minimum number is: 9

แก้ไข: ใน min_ele ลูปควรเป็น for (i = 1; i < n; i++) เพื่อกัน out-of-bounds