Skip to content

Instantly share code, notes, and snippets.

@Yurlov
Created June 17, 2016 11:48
Show Gist options
  • Save Yurlov/b756214481815cf070be1fe0fb9c2bbb to your computer and use it in GitHub Desktop.
Save Yurlov/b756214481815cf070be1fe0fb9c2bbb to your computer and use it in GitHub Desktop.
Prog.kiev.ua
import java.util.Arrays;
public class ArrayPositiveFinder
{
public static void main(String[] args) {
int[] array = {-1, 84, 0, -1, 27, -1};
int findFirstPositive = findFirstPositive(array);
int findLastPositive = findLastPositive(array);
System.out.println(Arrays.toString(array));
System.out.println("Index of first positive element : " + findFirstPositive);
System.out.println("Index of last positive element: " + findLastPositive);
}
private static int findFirstPositive(int[] array) {
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
return index + i;
}
}
return -1;
}
private static int findLastPositive(int[] array) {
int index = 0;
for (int i = array.length - 1; i > 0; i--) {
if (array[i] > 0) {
return index + i;
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment