Write a static method that, exchanges the first half of an array with the second
ID: 3680186 • Letter: W
Question
Write a static method
that, exchanges the first half of an array with the second half. (If there is an odd number of elements, the middle element is not moved.) For example, given the array
after calling switchHalves the array should look like this:
(Hint: Carefully work out an example with pencil and paper first. For instance, in an array of length 9 like the one above, you want to swap four pairs:
index 0 with index 5,
index 1 with index 6,
index 2 with index 7, and
index 3 with index 8.
Given the length, can you calculate the number of elements to swap? Can you calculate the starting index for the second "half"? Is the calculation different if there is an even number of elements?)
Explanation / Answer
public static void switchHalves(int[] numbers){
int n=numbers.length;
if(n%2==0){
int temp=0;
int k=n/2;
for(i=0;i<k && k<n;i++){
a[i]=temp;
a[i]=a[k]
a[k]=temp;}
}
else{
int k=n/2;
for(i=0;i<k && k<n;i++){
a[i]=temp;
a[i]=a[k+1]
a[k+1]=temp;}
}
}
}
yes we can calculate the number of elements to swap if length is given.
number of elements to swap is same for both cases wether length of array is even or odd i.e n/2
starting index of second half =n/2+1
calculation of number of element to swap and starting index of second half is same.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.