55package com .deepak .algorithms .Searching ;
66
77/**
8- * Class for LinearSearch implementation
9- * @author Deepak Malik
8+ * Linear Search implementation
9+ *
10+ * @author Deepak
1011 */
1112public class LinearSearch {
1213
13- /**
14- * Main method to start the flow of program
15- * @param args
16- */
17- public static void main (String [] args ) {
18- int [] nonSortedValues = {7 , 10 , 47 , 40 , 83 , 84 , 65 , 61 , 32 , 55 , 49 , 46 , 25 , 20 , 93 , 63 , 54 , 10 };
19- int iValueToBeSearched = 61 ;
20- System .out .println ("******************* LINEAR SEARCH *******************" );
21- performLinearSearch (nonSortedValues , iValueToBeSearched );
22- }
23-
2414 /**
2515 * <p>Linear Search is also called Sequential Search
2616 * Few point to note here,
27- * 1. It can be really slow with large number of elemets in the collection
17+ * 1. It can be really slow with large number of elements in the collection
2818 * ex. If we have 1000000 items in the list, on an average it will take 500000 number of comparisons
2919 * 2. To be used when we are not sure about the sort order of the list. </p>
3020 *
@@ -49,19 +39,15 @@ public static void main(String[] args) {
4939 * => For an array of size N, number of comparisons will be N/2
5040 * </p>
5141 */
52- private static void performLinearSearch (int [] iListOfValues , int iValueToBeSearched ) {
42+ public static int performLinearSearch (int [] listOfValues , int targetValue ) {
5343 int index = -1 ;
54- for (int i =0 ; i < iListOfValues .length ; i ++) {
55- if (iListOfValues [i ] == iValueToBeSearched ) {
44+ for (int i =0 ; i < listOfValues .length ; i ++) {
45+ if (listOfValues [i ] == targetValue ) {
5646 index = i ;
5747 break ;
5848 }
5949 }
60- if (index == -1 ) {
61- System .out .println ("Element not found in the collection" );
62- } else {
63- System .out .println ("Element found in the collection at index = " + index );
64- }
50+ return index ;
6551 }
6652
6753}
0 commit comments