Simple Example of Binary Search
package Practice;
public class BinarySearch {
public static void main(String[] args)
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
int number=10;
int li=0;
int hi=arr.length-1;
int mi=(li+hi)/2;
while (li<=mi){
if (arr[mi]==number){
System.out.println("item available at "+mi+" index position");
break;
}
else if (arr[mi]<number){
li=mi+1;
}
else {
hi=mi-1;
}
mi=(li+hi)/2;
}
if (li>hi){
System.out.println("Element not found");
}
}
}
Output :
package Practice;
public class BinarySearch {
public static void main(String[] args)
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
int number=10;
int li=0;
int hi=arr.length-1;
int mi=(li+hi)/2;
while (li<=mi){
if (arr[mi]==number){
System.out.println("item available at "+mi+" index position");
break;
}
else if (arr[mi]<number){
li=mi+1;
}
else {
hi=mi-1;
}
mi=(li+hi)/2;
}
if (li>hi){
System.out.println("Element not found");
}
}
}
Output :
click to next :
Sorting and Searching Programs
Start with your Choice
-Important
Programs for Freshers
- Palindrome Number
- Prime
Number
- Swapping
Number
- Leap Year
- Odd and
Even Number
- Fibonacci
Series
- Armstrong
Number
- Factorial
Number
- Print
Table
Learn Pattern Programs
- Alphabet
pattern program in java
- Star
Pattern Programs in Java
- Square
pattern programs in java
- Diamond
Star pattern programs in java
- Number
Pattern Programs in java
- Diagonal
pattern program in java
Click to learn Array Programs
- 4 ways to
print Array in Java
- 2-D Array
in Java
- Anonymous
Array in Java
- Single
Dimensional Array in Java
- Find
Second Largest Number in Array
- Delete an
Element in Array in Java
- Common
Element in Array in Java
- Missing
Element in Array
- Insert
Element in Array
- Reverse
Array in Java
- Merge
Two Array in Java
- Smallest
and Largest Elements in Array
- Find Odd
and Even Number in Array
No comments:
Post a Comment