对数进行排序java
时间: 2023-12-03 18:39:26 浏览: 27
以下是Java中对数组进行升序排序的两种方法:
1.使用Arrays.sort()方法
```java
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
Arrays.sort(arr);
System.out.println("Elements of array sorted in ascending order: " + Arrays.toString(arr));
```
输出结果为:
```
Elements of array sorted in ascending order: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
```
2.自定义排序方法
```java
public static void sortArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("Elements of array sorted in ascending order: " + Arrays.toString(arr));
}
```
调用方法:
```java
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
sortArray(arr);
```
输出结果为:
```
Elements of array sorted in ascending order: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)