Find the First Negative Number of an Array
The code I came up with works if there is only one negative number. If there is more than one negative number, I get a throw exception. Which portion of the code should I be focusing on? Or is there another loop statement needed?
Code:
for (int i = 0; i < a.length; i++) {
if (a[i] < 0)
negativeNumbers ++;
}
int j = a.length - 1;
while (j >= 0) {
if (a[j - negativeNumbers] < 0) {
a[j] = 0;
a[j - 1] = a[j - negativeNumbers];
negativeNumbers--;
j--;
}
else
a[j] = a[j - negativeNumbers];
j--;
}
Any guidance is greatly appreciated.