-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearSearchWithSentinel.java
53 lines (38 loc) · 1.15 KB
/
LinearSearchWithSentinel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
import java.util.Scanner;
public class LinearSearchWithSentinel
{
private LinearSearchWithSentinel(){} //this class is not for instantiation
public static int search(int[] a, int n, int searchValue)
{
a[n] = searchValue;
int i=0;
while( searchValue!=a[i] )
i++;
if(i<n)
return i;
else
return -1;
}
public static void main(String[] args)
{
int i,n,searchValue, index;
int[] a = new int[100];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements : ");
n = scan.nextInt();
System.out.println("Enter the elements - ");
for(i=0; i<n; i++)
a[i] = scan.nextInt();
System.out.print("Enter the search value : ");
searchValue = scan.nextInt();
index = search(a, n, searchValue);
if( index == -1 )
System.out.println("Value " + searchValue + " not present in the array");
else
System.out.println("Value " + searchValue + " present at index " + index);
}
}