插入排序倒序java
时间: 2023-12-07 21:39:29 浏览: 37
以下是Java中实现插入排序倒序的代码示例:
```java
public class InsertionSortReverse {
public static void main(String[] args) {
int[] arr = {5, 2, 4, 6, 1, 3};
insertionSortReverse(arr);
System.out.println(Arrays.toString(arr)); // 输出:[6, 5, 4, 3, 2, 1]
}
public static void insertionSortReverse(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] < key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
```
相关问题
java set排序正序倒序
Java中的Set是一个无序的集合,不支持像List一样的按照索引位置排序的方法。但是可以使用TreeSet来实现有序的Set集合。TreeSet是一个有序的集合,它默认按照元素的自然排序方式(Comparable接口)来排序,也可以通过传递Comparator对象来自定义排序方式。
要将TreeSet按照正序排列,只需要使用默认的构造方法创建一个TreeSet即可:Set<MyClass> mySet = new TreeSet<MyClass>(); 这样插入的元素会根据实现Comparable接口的compareTo方法自动排序。
如果需要按照自己定义的排序方式来排序,可以实现Comparator接口来比较元素。例如:
```
Set<MyClass> mySet = new TreeSet<MyClass>(new Comparator<MyClass>() {
@Override
public int compare(MyClass o1, MyClass o2) {
return o1.getAge() - o2.getAge(); //按照年龄从小到大排序
}
});
```
要将TreeSet按照倒序排列,可以使用TreeSet的descendingSet()方法将集合反转。例如:
```
Set<MyClass> mySet = new TreeSet<MyClass>(Collections.reverseOrder());
mySet.add(xxx);
Set<MyClass> reverseSet = ((TreeSet<MyClass>) mySet).descendingSet();
```
map倒序遍历java
在Java中,Map数据结构的默认遍历顺序并不是按照插入顺序或键值对的自然排序,而是根据Map的具体实现(如HashMap或TreeMap)的内部逻辑。如果你想按某种特定顺序遍历Map,比如从大到小或者从小到大,你需要采取一些额外的步骤。
如果你想实现Map(如HashMap)的倒序遍历,一种常见的做法是使用迭代器和Comparator。例如,如果你有一个HashMap<String, Integer>,你可以这样做:
```java
import java.util.*;
Map<String, Integer> map = new HashMap<>();
// 假设已经添加了一些元素
// 获取Map的EntrySet,这是可迭代的
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
// 创建一个自定义的Comparator,用于降序排列
Collections.sort(entrySet, Collections.reverseOrder());
// 遍历倒序的entrySet
for (Map.Entry<String, Integer> entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)