Tìm kiếm đơn giản trong Python là gì?

Các thuật toán tìm kiếm được sử dụng để tìm kiếm hoặc tìm một hoặc nhiều phần tử từ tập dữ liệu. Các loại thuật toán này được sử dụng để tìm các phần tử từ một cấu trúc dữ liệu cụ thể

Mảng cần tìm
  1. Bắt đầu từ phần tử đầu tiên, so sánh k với từng phần tử x.
    So sánh với từng phần tử
  2. Nếu x == k, trả lại chỉ mục.
    Đã tìm thấy phần tử
  3. Khác, không tìm thấy trả lại

Thuật toán tìm kiếm tuyến tính

LinearSearch[array, key]
  for each item in the array
    if item == value
      return its index

Ví dụ về Python, Java và C/C++

# Linear Search in Python


def linearSearch[array, n, x]:

    # Going through array sequencially
    for i in range[0, n]:
        if [array[i] == x]:
            return i
    return -1


array = [2, 4, 0, 1, 9]
x = 1
n = len[array]
result = linearSearch[array, n, x]
if[result == -1]:
    print["Element not found"]
else:
    print["Element found at index: ", result]

// Linear Search in Java

class LinearSearch {
  public static int linearSearch[int array[], int x] {
  int n = array.length;

  // Going through array sequencially
  for [int i = 0; i < n; i++] {
    if [array[i] == x]
    return i;
  }
  return -1;
  }

  public static void main[String args[]] {
  int array[] = { 2, 4, 0, 1, 9 };
  int x = 1;

  int result = linearSearch[array, x];

  if [result == -1]
    System.out.print["Element not found"];
  else
    System.out.print["Element found at index: " + result];
  }
}

// Linear Search in C

#include 

int search[int array[], int n, int x] {
  
  // Going through array sequencially
  for [int i = 0; i < n; i++]
    if [array[i] == x]
      return i;
  return -1;
}

int main[] {
  int array[] = {2, 4, 0, 1, 9};
  int x = 1;
  int n = sizeof[array] / sizeof[array[0]];

  int result = search[array, n, x];

  [result == -1] ? printf["Element not found"] : printf["Element found at index: %d", result];
}

// Linear Search in C++

#include 
using namespace std;

int search[int array[], int n, int x] {

  // Going through array sequencially
  for [int i = 0; i < n; i++]
    if [array[i] == x]
      return i;
  return -1;
}

int main[] {
  int array[] = {2, 4, 0, 1, 9};
  int x = 1;
  int n = sizeof[array] / sizeof[array[0]];

  int result = search[array, n, x];

  [result == -1] ? cout 

Chủ Đề