1. Description
Given a list of
n numbers in non-decreasing order A={a1,a2,⋯,an} such that a1≤a2≤⋯≤an and a number x, the objective is to determine if x is present in the list A2. Algorithm
- Algorithm 1.
- Linear Search Algorithm
- Iterate through n numbers to find the x.
- Linear Search Algorithm
- Algorithm 2.
- Binary Search Algorithm.
Algorithm 1.
- O(n)
Algorithm 2.
- O(logn)
4. Implementation
Algorithm 1.
public class LinearSearch {public static void Result(int Seq[],int Len,int x){for(int i=0;i<Len;i++){if(x==Seq[i]){System.out.println(x+" is present at seq["+i+"]");break;}else if(x!=Seq[i]&&i==Len-1){System.out.println(x+" is not present in seq");}}}public static void main(String[] args){int Seq[]={4,33,40,44,45,45,55,60,99};int Len=Seq.length;Result(Seq,Len,55); Result(Seq,Len,70);}
}
Result of Algorithm1:
Algorithm 2-Implementation1
public class BinarySearch1 {public static void BinarySearch(int Seq[],int x,int left,int right){ int mid=(left+right)/2;if(left==right-1&&x!=Seq[left]&&x!=Seq[right]) //如果只剩两个数,两个数都不是x,那么x不在数组Seq中{System.out.println(x+" is not present in Seq");}else if(x==Seq[mid]){System.out.println(x+" is present at Seq["+mid+"]");}else if(x>Seq[mid]){ System.out.println(x+" is between seq["+mid+"] and Seq["+right+"]");left=mid;BinarySearch(Seq,x,left,right);}else if(x<Seq[mid]){System.out.println(x+" is between seq["+left+"] and Seq["+mid+"]");right=mid;BinarySearch(Seq,x,left,right);}}public static void main(String args[]){int Seq[]={1,2,3,3,8,9,11,56,89};int left=0, right=Seq.length-1;System.out.println("Test whether 56 is present in seq:");BinarySearch(Seq,56,left,right);System.out.println("Test whether 7 is present in seq:");BinarySearch(Seq,7,left,right);}
}
Algorithm 2-Implementation2
public class BinarySearch2 {public static void BinarySearch(int Seq[],int x){int left=0;int right=Seq.length-1;int mid=(left+right)/2;while(true){if(x==Seq[mid]){System.out.println(x+" is present at Seq["+mid+"]");break;}else if(x>Seq[mid]){System.out.println(x+" is between seq["+mid+"] and Seq[" +right+"]"); left=mid+1;if(left>=right){System.out.println(x+" is not in seq");break;}mid=(left+right)/2;}else if(x<Seq[mid]){System.out.println(x+" is between seq["+left+"] and Seq[" +mid+"]"); right=mid-1; if(left>=right){System.out.println(x+" is not in seq");break;}mid=(left+right)/2;}}}public static void main(String[] args){int Seq[]={4,33,40,44,45,45,55,60,99}; System.out.println("Test whether 56 is present in seq:"); BinarySearch(Seq,55); System.out.println("Test whether 7 is present in seq:"); BinarySearch(Seq,70); }
}
Result of Both implementation1 and implementation2: