Reputation: 41
This code prints the first occurence of element 'k' in the array properly but the question I'm doing wants me to print -1 if the element 'k' is entirely not present in the array. I know its easy but I'm just stuck and its frustatiting any help?
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
}
for(int i=0;i<n;i++) {
if(arr[i]==k) {
System.out.println(i);
break;
}
}
Upvotes: 0
Views: 1543
Reputation: 109547
Use Arrays#binarySearch:
int firstIndexOf(int[] sortedArray, int x) {
int p = Arrays.binarySearch(sortedArray, x);
if (p < 0) {
return -1;
}
while (p > 0 && sortedArray[p - 1] == x) {
--p;
}
return p;
}
Binary search splits the searched range in half repetively looking in which half to continue. It returns either the found position or the complement (~p) of the insert position.
Upvotes: 1
Reputation: 11120
What you are asking in the title, and what you are asking in the post body, are two different questions; however, if we will follow your question's body, that has nothing to do with binary search, and introducing boolean flag would get you what you are asking for:
boolean notFound = true;
for(int i=0; i<n; i++) {
if(arr[i] == k) {
System.out.println(i);
notFound = false;
break;
}
}
if(notFound) System.out.println("-1");
Upvotes: 0
Reputation: 16
int findOccurenceOfElemet(int[] a, int k) {
if(a.length == 0) {
return -1;
}
for(int i = 0; i < a.length; i++) {
if(a[i] == k) {
return i;
}
}
//return -1 if element not found
return -1;
}
Upvotes: 0