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
tabX[]before you started withfor()?