java编写实现数组转置。源数组:1,2,3,4,5,6 转置之后的数组:6,5,4,3,2,1
时间: 2024-06-14 16:06:07 浏览: 15
以下是Java实现数组转置的代码示例:
```java
public class Exchange {
public static void main(String[] args) {
int[][] arrayA = {{1, 2, 3}, {4, 5, 6}};
int[][] arrayB = new int[arrayA[0].length][arrayA.length];
// 实现数组转置
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < arrayA[i].length; j++) {
arrayB[j][i] = arrayA[i][j];
}
}
// 输出转置后的数组
for (int i = 0; i < arrayB.length; i++) {
for (int j = 0; j < arrayB[i].length; j++) {
System.out.print(arrayB[i][j] + " ");
}
System.out.println();
}
}
}
```
输出结果为:
```
1 4
2 5
3 6
```
相关问题
将一个给定的整型数组转置输出, 例如: 源数组,1 2 3 4 5 6 转置之后的数组,6 5 4 3 2 1
以下是一个将整型数组进行转置输出的示例代码:
```python
arr = [1, 2, 3, 4, 5, 6]
reversed_arr = arr[::-1]
print(reversed_arr)
```
输出结果为:`[6, 5, 4, 3, 2, 1]`
这里使用了 Python 中的切片操作 `[::-1]`,它可以将数组反转。`arr[::-1]` 表示从数组末尾开始,每次取一个元素,直到数组开头,相当于将整个数组反转。
编程实现:从键盘输入一个整型数组的长度和数组元素,然后将其转置,例如:源数组123456,转置之后的数组654321,最后对数组进行排序,并且输出。 程序运行结果:请输入数组长度:5 请输入数组元素:15324数组转置之后:4 2 3 5 1数组排序之后:1 2 3 4 5 java
下面是 Java 语言的实现代码:
```java
import java.util.Scanner;
import java.util.Arrays;
public class ArrayTransposeSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 读取数组长度
System.out.print("请输入数组长度:");
int n = input.nextInt();
// 读取数组元素
System.out.print("请输入数组元素:");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
// 数组转置
for (int i = 0, j = n - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// 数组排序
Arrays.sort(arr);
// 输出结果
System.out.print("数组转置之后:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.print("数组排序之后:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
```
运行结果:
```
请输入数组长度:5
请输入数组元素:1 5 3 2 4
数组转置之后:4 2 3 5 1
数组排序之后:1 2 3 4 5
```
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)