把int数组按照降序排列代码
时间: 2023-12-21 15:03:48 浏览: 83
以下是将 int 数组按照降序排列的代码示例:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = { 3, 5, 1, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// 使用标准库中的 sort 函数,降序排列数组
sort(arr, arr + n, greater<int>());
// 输出排序后的数组
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:5 4 3 2 1
相关问题
用java把int数组按照降序排列代码,用到sort和comparator
以下是使用 Java 中的 sort 和 Comparator 接口将 int 数组按照降序排列的代码示例:
```java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
int[] arr = { 3, 5, 1, 4, 2 };
// 使用 Arrays.sort 函数,降序排列数组
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return b - a;
}
});
// 输出排序后的数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果为:5 4 3 2 1
用java把double数组按照降序排列代码,用到sort和comparator
以下是使用 Java 中的 sort 和 Comparator 接口将 double 数组按照降序排列的代码示例:
```java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
double[] arr = { 3.2, 5.7, 1.4, 4.1, 2.9 };
// 使用 Arrays.sort 函数,降序排列数组
Arrays.sort(arr, new Comparator<Double>() {
@Override
public int compare(Double a, Double b) {
return Double.compare(b, a);
}
});
// 输出排序后的数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果为:5.7 4.1 3.2 2.9 1.4
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)