Reputation: 55
I've been looking at a for-loop that reverses the elements in an array, but I do not quite understand what's going on inside it. This is the code:
int middleIndex = (array.length) / 2;
for (int i = 0; i < middleIndex; i++) {
int temporaryVariable = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temporaryVariable;
}
What exactly does the two lines below int temporaryVariable = array[i] do? How exactly does it reverse the elements?
Upvotes: 0
Views: 121
Reputation: 55
another part was to return the second biggest number, but for some reason it returns the third biggest number, which is really weird.
This is the code:
public static int returnSecondBiggest(int[] array) {
int largestElement = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largestElement) {
largestElement = array[i];
}
}
int secondBiggest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > secondBiggest && array[i] != largestElement) {
secondBiggest = array[i];
}
}
return secondBiggest;
}
How does it return the third when the code should return the second? I'm so lost.
Upvotes: 0
Reputation: 22128
First of all remember that array indexes start from 0.
So the index of the last element is the array.length - 1
.
Those 3 lines are swapping the first item with the last item, then the 2nd item with the 2nd-from-last item, etc. The temporaryVariable
is used as a temporary place to store one of the values during swapping, so that it doesn't get lost when it is overwritten by the other value.
Take a copy of the value at i
:
int temporaryVariable = array[i];
Put item i
from the end of the array (array.length - 1 - i
) instead of it.
array[i] = array[array.length - 1 - i];
Put the temporarily stored item which was item i
at i
from the end (array.length - 1 - i
).
array[array.length - 1 - i] = temporaryVariable;
The loop stops when i
reaches the middle of the array. (If the array has an odd number of elements the middle one stays where it is.)
Upvotes: 0
Reputation: 1109
This algorithm is taking N/2 iterations of swapping values stored in an array. It starts from the beggining of the array (Index 0) and goes until its half(index N/2). It swaps the first element(indexed 0) with the last one (indexed N - 1 - 0), then swaps the second element(indexed 0 + 1) with the one before the last one(indexed N - 1 - (0 + 1)), and so on.
Upvotes: 0
Reputation: 2447
The 2 lines after int temporaryVariable = array[i];
simply swap the i'th element with the i'th from last element, and we run this loop half time the number of elements in array.
Upvotes: 1
Reputation: 9786
It effectively reverses the elements of the array by swapping first
with last
element, second
with second_last
etc. In this way the number of operations are ayrray_length / 2
.
Upvotes: 1