java - 使用 Comparable[] 作为参数创建插入排序方法时遇到问题
问题描述
对于for循环主体中的第一行curr = arr [i],我的insertionSort算法不断收到不兼容的类型错误。不知道如何解决这个问题,我认为 Comparable Object 与整数一起使用。
public void insertionSort(Comparable[]arr, int lowIndex, int highIndex , boolean reversed){
//if false is passed in for the boolean parameter reversed then the array should be sorted in ascending order
if(!reversed){
//int[] newArr = new int[highIndex];
int curr;
int j;
//for loop to pass through the array with starting position set to lowIndex and the terminating condition
//set to highIndex + 1
for(int i = lowIndex; i < highIndex + 1; i++){
curr = arr[i];
j = i - 1;
//curr is set to a[i] and j is set to i - 1, if curr is less than the previous index then they will be
//swapped
while(j >= lowIndex && arr[j].compareTo(curr) > 0){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = curr;
}
}
解决方案
好吧,您有一个数组,Comparable
并且您期望可以将其分配给curr
, 类型int
。你如何期望一个类型的对象Comparable
神奇地变成一个整数?
顺便说一句,您的算法似乎没有进行插入排序,即冒泡排序。
推荐阅读
- windows - 未检测到通过组策略的防火墙规则
- javascript - React Native - 无法从 AsyncStorage.getItem() 获取数据
- android - 在 Android 外部存储中创建文件夹
- c++ - make_unique 无法访问静态成员中的私有构造函数
- flutter - 一键放大和缩小
- sql - 可配置的 SQL GROUP BY 变量
- java - 配置 Spring Boot 时 classpath:/some/packages 与 file:/some/url 之间的区别
- python - 搜索每个子数组中的最小值的函数
- android - 尝试集成 AdMob (IronSource) 后无法在 Unity 中构建 APK
- android - scrollTo 在 Android 上没有动画