Reputation: 25
Any solution for this i need to swap element x with y in unsorted array ,x and y are in array
I have this error for array lengths >= 6. The code works for tabX[] < 6 length.
java.lang.ArrayIndexOutOfBoundsException:-6.
int tabX[] = {
20, 40, 50, 60, 80, 70
};
int elemA[];
int elemB[];
int sumA = 0;
int sumB = 0;
int tmp, lastButOne;
Arrays.sort(tabX);
while (sumA > sumB || sumA == 0 || sumB == 0) {
for (int i = 0; i < tabX.length; i++) {
sumA = 0;
sumB = 0;
elemA = new int[tabX.length - (i + 1)];
elemB = new int[i + 1];
for (int j = 0; j < tabX.length - (i + 1); j++) {
elemA[j] = tabX[j];
sumA += elemA[j];
}
for (int k = 0; k < elemB.length; k++) {
elemB[k] = tabX[tabX.length - (k + 1)]; //i
sumB += tabX[tabX.length - (k + 1)];
}
if (sumA == sumB) {
System.out.println("Secventa A = " + Arrays.toString(elemA));
System.out.println("Secventa B = " + Arrays.toString(elemB));
break;
} else if (sumA < sumB) {
System.out.println("Not a solution");
break;
}
/************ Swap element in array****************/
lastButOne = tabX[tabX.length - (i + 2)];
int indexOfLastButOne = Arrays.binarySearch(tabX, lastButOne);
tmp = tabX[i];
tabX[indexOfLastButOne] = tmp; //here is error
tabX[i] = lastButOne;
} //for
} //while
Upvotes: 1
Views: 2227
Reputation: 479
Well, that's exactly how Arrays.binarySearch works: when the actual element you're asking for isn't there, you get the -(insertion point) - 1, which happens to be -6 in your case.
But also: binarySearch assumes the elements are sorted, so if they're not, it can indeed happen that it isn't found, even if the value is in the list.
Upvotes: 2
Reputation: 14159
It would be helpfull if you pointed out where the exception is thrown (add a comment like // AIOOBE here
. From looking at your code, I guess you get a negative return value from Arrays.binarySearch()
:
int indexOfLastButOne = Arrays.binarySearch(tabX, lastButOne);
...
tabX[indexOfLastButOne] = tmp; // ArrayOutOfBoundsException
From the documentation of Arrays.binarySearch
: returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
Upvotes: 1