Java implementation code for array flipping
1. Java provides some toolkits to realize array flipping. I won't repeat reverse here...
2. You can also assign a new array through a flashback loop, for example
private static String[] reverseArray(String[] Array) { String[] new_array = new String[Array.length]; for (int i = 0; i < Array.length; i++) { // 反转后数组的第一个元素等于源数组的最后一个元素: new_array[i] = Array[Array.length - i - 1]; } return new_array; }
3. But can the efficiency be higher, and how to flip on the same array
For example, arrays: A, B, C, D, e, F, G
Return result: G, a
Analysis: array length is 7
Corresponding to the array tag, the array starts from 0, that is, 0, 1, 2, 3, 4, 5, 6
When the length is singular, the middle bits do not need to be interchanged, that is, D (4) does not need to be interchanged, that is, 7 / 2 rounding result 3, 3 + 1 does not need to be interchanged, that is, length / 2 + 1 does not need to be interchanged
When the length is an even number, it does not need to be considered and all are exchanged
Summary: the data to be exchanged are 0 ~ (length / 2 - 1) and length / 2 ~ (length - 1)
Set the circulatory system I = 0 and the threshold value is lenth / 2 - 1. At the same time, flashback and obtain the following parameters for exchange.
public static void main(String[] args) { String[] num = {"1","2","3","4","5","6"}; for (int i = 0; i <= num.length / 2 - 1; i++) { String temp1 = num[i]; String temp2 = num[num.length - i - 1]; num[i] = temp2; num[num.length - i - 1] = temp1; } System.out.println(Arrays.asList(num).toString()); }
Just think of these for the time being, and hide the knowledge points. The difference between value passing and reference passing in Java....
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.