Skip to content

Commit ce6b434

Browse files
committed
Example of Linear Search Algorithm
1 parent 4dec752 commit ce6b434

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

‎src/LinearSearch/LinearSearch.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package LinearSearch;
2+
3+
public class LinearSearch {
4+
public static void main(String[] args) {
5+
6+
int[] array = {34,56,78,94,64,33};
7+
int target = 323;
8+
int answer = linearSearch(array,target);
9+
System.out.println(answer);
10+
}
11+
12+
//Search in the Array: Return the index if item found. Return -1 is item not found
13+
static int linearSearch(int[] array, int integer){
14+
if (array.length == 0){
15+
return -1;
16+
}
17+
18+
for (int index = 0; index < array.length; index++){
19+
//Check for the element
20+
int element = array[index];
21+
if (element == integer){
22+
return index;
23+
}
24+
}
25+
26+
return -1;
27+
}
28+
}

0 commit comments

Comments
 (0)