# 線性搜尋

• 線性搜尋
• 二進位制搜尋

## 線性搜尋

``````LINEAR_SEARCH(A，N，VAL)

SET POS = I
列印POS
轉到第6步
[IF結束]
SET I = I + 1
[迴圈結束]

列印「值不在陣列中」
[IF結束]

``````

C語言實現程式碼 -

``````#include<stdio.h>
void main ()
{
int a[10] = {10, 23, 40, 1, 2, 0, 14, 13, 50, 9};
int item, i,flag;
printf("Enter 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("Item found at location %d\n",flag);
}
else
{
}
}
``````

``````Enter Item which is to be searched
20
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

}
}
``````

``````Enter Item ?
23
Item found at location 2
Enter Item ?
22
``````

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");
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

}
}
``````

``````Enter the item value
78
Item Found at Location 10

Enter the item value
22
``````

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 :
``````Enter the item which you want to search 2