个性化阅读
专注于IT技术分析

线性搜索算法

本文概述

搜索是在列表中查找某些特定元素的过程。如果该元素存在于列表中, 则该过程称为成功, 并且该过程返回该元素的位置, 否则, 搜索称为不成功。

有两种流行的搜索方法被广泛使用, 以便将某些项目搜索到列表中。但是, 算法的选择取决于列表的排列。

  • 线性搜寻
  • 二元搜寻

线性搜寻

线性搜索是最简单的搜索算法, 通常称为顺序搜索。在这种类型的搜索中, 我们只需完全遍历列表, 然后将列表中的每个元素与要查找其位置的项目进行匹配即可。如果找到匹配项, 则返回项目的位置, 否则算法返回NULL。

线性搜索通常用于搜索未排序项目的无序列表。线性搜索算法如下。

算法

  • 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)

C程序

#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 searched
20
Item not found
Enter Item which is to be searched
23
Item 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 ?
23
Item found at location 2
Enter Item ?
22
Item 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 value
78
Item Found at Location 10

Enter the item value 
22
Item 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 2
Item found at location 2
Enter the item which you want to search 101 
Item not found
赞(0)
未经允许不得转载:srcmini » 线性搜索算法

评论 抢沙发

评论前必须登录!