>but it's not showing the 5th position.
Your search only looks for the first occurance. To find subsequent matches, you need to continue the search until the end because you don't know how many matching items there are in the list:
public class Main {
public static void main ( String[] args ) {
int[] array = {20,55,10,2,100,2};
int target = 2;
for ( int i = 0; i < array.length; i++ ) {
if ( array[i] == target )
System.out.println ( target + " found at index " + i );
}
}
} Concerning your second question, the biggest problem is that the array is not sorted. Binary search requires that the input list be in sorted order. Once the array is sorted, the algorithm would look like this:
public class Main {
public static void main ( String[] args ) {
int[] array = {2,2,10,20,55,100};
int target = 2;
int left = 0;
int right = array.length - 1;
int mid = -1;
while ( left <= right ) {
mid = ( left + right ) / 2;
if ( target == array[mid] )
break;
else if ( target < array[mid] )
right = mid - 1;
else
left = mid + 1;
}
if ( mid != -1 )
System.out.println ( target + " found at index " + mid );
else
System.out.println ( target + " not found" );
}
} Notice in particular how the loop condition is such that left never crosses right and how mid is calculated for every iteration of the loop. The whole point of the binary search is to cut the search area in half by dividing it in the middle based on whether the middle item is larger than or smaller than the target.