Monday 15 May 2017

1. Linear Search

1. What is Linear Search
A simple approach is to do linear search, i.e
  1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
  2. If x matches with an element, return the index.
  3. If x doesn’t match with any of elements, return -1.
The time complexity of above algorithm is O(n).




public class LinearSearch {

public static void main(String[] args) {
int array[] = {13, 48, 7, 4, 15, 25, 11};
int ele = 25;
int index = linearSearch(array, ele);
System.out.println("index is "+index);
}
public static int linearSearch(int array[], int ele){
for(int i=0; i<array.length; i++){
if(array[i] == ele)
return i;
}
return -1;
}

}

No comments:

Post a Comment

3. Java Program to create Binary Tree