for (int i = 0; i <= sizeOfArr; i++) {
for (int j = sizeOfArr; j >= 0; j--) {
backwards[j]=arr[i];
}
}
Although looping through the list twice is one way of doing it, the faster way of doing it is to only loop once (or just use Collections.reverse)
Try it with one loop, it's much easier to read and performs better (your double loop is probably overwriting values in the backward array):
for (int i = 0; i < arraysize; i++){
backward[arraysize-i-1] = arr[i];
}
(Wrote the above on my phone, so apologies for any potential errors)
Swap items up until you reach the midpoint, like this:
for (i = 0; i < sizeOfArr / 2; i++) {
int temp = arr[i];
array[i] = arr[sizeOfArr - 1 - i];
arr[sizeOfArr - 1 - i] = temp;
}
Amir Anwar
Python and Android developer
The first thing is that you need to adjust
i <= sizeOfArrtoi < sizeOfArr, this is because you started counting from 0i=0, so e.g. if we have an array of size = 5,ishould take 5 values only resulting in 5 rounds in the for loop.. meaning : 0,1,2,3,4.... 5 values... but if you use <=iwill take 6 values so it will try to get a value from the array at index=6 in the linebackwards[j]=arr[i];which actually doesn't exist ...resulting in an error. Second thing is that the second for loop is wrong... imagine with me the code is executing and the computer is now in the first loop ... i = 0 ... then it enters the second loop... j = 5... backwards index no . 5 is updated with first member of original array... then j = 4. (Still i = 0).. then backwards index no . 4 is updated with ALSO the first member of original array resulting in an array with only one value for all its members...and when i becomes = 1.. the backwards array will be overwritten with the second member of original array ... and so on ... at the end you will have an array full of same member which will be the last member of original array... this is not the desired result off courseloo