首页 > 解决方案 > 使用 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;
        }

    }

标签: java

解决方案


好吧,您有一个数组,Comparable并且您期望可以将其分配给curr, 类型int。你如何期望一个类型的对象Comparable神奇地变成一个整数?

顺便说一句,您的算法似乎没有进行插入排序,即冒泡排序。


推荐阅读