自己重新定义两个方法(不可以是java自带的方法) 方法1可以排序一个数组(30分) 方法2可以遍历一个数组(20分) 定义测试类,可以调用两个方法,实现已定义好的数组的排序和遍历,输出排序后的数组。
时间: 2024-02-04 19:03:40 浏览: 85
好的,下面是Java代码实现:
```java
public class ArrayUtils {
// 方法1:排序一个数组
public static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// 方法2:遍历一个数组
public static void traverse(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
public class TestArrayUtils {
public static void main(String[] args) {
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
System.out.println("原始数组:");
ArrayUtils.traverse(arr);
System.out.println("排序后的数组:");
ArrayUtils.sort(arr);
ArrayUtils.traverse(arr);
}
}
```
输出结果:
```
原始数组:
3 1 4 1 5 9 2 6 5 3 5
排序后的数组:
1 1 2 3 3 4 5 5 5 6 9
```
这里的排序方法是使用了冒泡排序算法,如果需要其他排序算法可以另外编写。另外,题目中没有具体说明排序方式,所以这里使用了默认的升序排序方式。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)