Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 36 additions & 10 deletions LinearSearch.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,41 @@
/*
SAMPLE OUTPUT(of the following code):
Element found at index 5
*/
public class LinearSearch {
//linearSearch() returns index of array if element is found else "-1" if element can't be found in array

static int linearSearch(int arr[],int ele){

int numberOfElements = arr.length;

for(int index=0;index<numberOfElements;index++){
if(arr[index] == ele){
return index;
}
}

return -1;
}
public static void main(String args[]){
int array[] = {1,2,3,4,6};
int size = array.length;
int value = 3;

for (int i=0 ;i< size-1; i++){
if(array[i]==value){
System.out.println("Element found index is :"+ i);
}else{
System.out.println("Element not found");
}
int sampleArray[] = {11,-1,23,35,42,67,84,99,202}; //sample list of elements in array
int element = 67; //element to search in array (list of numbers)

int searchResult = linearSearch(sampleArray, element); //result of the linearSearch()

if(searchResult == -1){
System.out.println("Element not found in array");
}else{
System.out.println("Element found at index "+searchResult);
}
}
}
/*
IMPLEMENTATION OF LINEAR-SEARCH (USING CONCEPT OF FUNCTIONS)


EXPLANATION:
In this java-code ,linear search is implemented thorugh functions which takes element to search(int ele) and elements in array(int arr[]) as parameters and returns postion of element in an array if element is found otherwise returns "-1" as a flag for not able to find element.

NOTE: this code is implemented for integeral elements.
*/
21 changes: 21 additions & 0 deletions linearSearch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Lineau Search Documentation

Linear Search is an element searching algorithm. This searching algorithm finds element in a list/array(number of elements) in a linear fashion(i.e. linearly). This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n) where n is the number of items.Advantage of using this algorithm is that it can be applied to unordered list of elements(i.e. unsorted elements in an array)

## Pseudocode

Suppose A is an array of N values and ELE is an element we want to search in array.


```
For I = 0 to N - 2
If (A(I) == ele)
return found element's Location
End-If
End-For

return element not found in array

```

### Linear Search does roughly N comparisons in order to find location of element in a array(i.e. list).