Linear serch in JAVA:
public class LLinearSearch
{
public static int linerSearch(int[]
arr, int key){
int size
= arr.length;
for(int i=0;i<size;i++){
if(arr[i]
== key){
return i;
}
}
return -1;
}
public static void main(String
a[]){
int[]
arr1= {23,45,21,55,234,1,34,90};
int searchKey
= 34;
System.out.println("Key
"+searchKey+" found at index: "+linerSearch(arr1, searchKey));
int[]
arr2= {123,445,421,595,2134,41,304,190};
searchKey
= 421;
System.out.println("Key
"+searchKey+" found at index: "+linerSearch(arr2, searchKey));
}
}
Binary serch In JAVA:
public class BinarySearch
{
public int binarySearch(int[]
inputArr, int key) {
int start
= 0;
int end
= inputArr.length - 1;
while (start
<= end) {
int mid
= (start + end) / 2;
if (key
== inputArr[mid]) {
return mid;
}
if (key
< inputArr[mid]) {
end
= mid - 1;
}
else {
start
= mid + 1;
}
}
return -1;
}
public static void main(String[]
args) {
BinarySearch
mb = new BinarySearch();
int[]
arr = {2, 4, 6, 8, 10, 12, 14, 16};
System.out.println("Key
14's position: "+mb.binarySearch(arr, 14));
int[]
arr1 = {6,34,78,123,432,900};
System.out.println("Key
432's position: "+mb.binarySearch(arr1, 432));
}
}
No comments:
Post a Comment