本文概述
- 线性搜寻
- 算法
- C程序
有两种流行的搜索方法被广泛使用, 以便将某些项目搜索到列表中。但是, 算法的选择取决于列表的排列。
- 线性搜寻
- 二元搜寻
线性搜索通常用于搜索未排序项目的无序列表。线性搜索算法如下。
算法
- LINEAR_SEARCH(A, N, VAL)
- 步骤1:[INITIALIZE] SET POS = -1
- 步骤2:[INITIALIZE] SET I = 1
- 步骤3:在I < = N时重复步骤4
- 步骤4:如果A [I] = VAL SET POS = I PRINT POS, 请转到步骤6 [IF结束] SET I = I + 1 [LOOP LOOP]
- 步骤5:如果POS = -1, 则打印“值不代表数组” [IF结束]
- 步骤6:退出
复杂 | 最好的情况 | 平均情况 | 最差的情况 |
---|---|---|---|
Time | O(1) | O(n) | O(n) |
Space | O(1) |
#include<
stdio.h>
void main (){ int a[10] = {10, 23, 40, 1, 2, 0, 14, 13, 50, 9};
int item, i, flag;
printf("\nEnter Item which is to be searched\n");
scanf("%d", &
item);
for (i = 0;
i<
10;
i++) {if(a[i] == item) {flag = i+1;
break;
} else flag = 0;
} if(flag != 0) {printf("\nItem found at location %d\n", flag);
} else {printf("\nItem not found\n");
}}
输出:
Enter Item which is to be searched20Item not foundEnter Item which is to be searched23Item found at location 2
Java程序
import java.util.Scanner;
public class Leniear_Search {public static void main(String[] args) { int[] arr = {10, 23, 15, 8, 4, 3, 25, 30, 34, 2, 19};
int item, flag=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Item ?");
item = sc.nextInt();
for(int i = 0;
i<
10;
i++) {if(arr[i]==item){flag = i+1;
break;
}else flag = 0;
} if(flag != 0) {System.out.println("Item found at location" + flag);
} else System.out.println("Item not found");
}}
输出:
Enter Item ?23Item found at location 2Enter Item ?22Item not found
C#程序
using System;
public class LinearSearch{ public static void Main() {int item, flag = 0;
int[]a= {10, 23, 5, 90, 89, 34, 12, 34, 1, 78};
Console.WriteLine("Enter the item value");
item = Convert.ToInt32(Console.ReadLine());
for(int i=0;
i<
10;
i++){if(item == a[i]){flag = i+1;
break;
}else flag = 0;
}if(flag != 0 ) {Console.WriteLine("Item Found at Location " + flag);
}else Console.WriteLine("Item Not Found");
}}
输出:
Enter the item value78Item Found at Location 10Enter the item value 22Item not found
Python程序
arr = [10, 2, 3, 4, 23, 5, 21, 45, 90, 100];
item = int(input("Enter the item which you want to search "));
for i in range (0, len(arr)): if arr[i] == item:flag = i+1;
break;
else: flag = 0;
if flag != 0: print("Item found at location %d" % (flag));
else : print("Item not found");
【线性搜索算法】输出:
Enter the item which you want to search 2Item found at location 2Enter the item which you want to search 101 Item not found
推荐阅读
- 队列的链表实现
- Android打造随意层级树形控件考验你的数据结构和设计
- 插入排序算法实现
- 堆排序算法实现
- 图论(图Graph的表示方法)
- 栈的链表实现
- 数据结构(图(Graph))
- 栈的数组实现
- 数据结构之双链表