创建Comparable []作为参数的insertSort方法创建麻烦

时间:2019-03-03 01:29:05

标签: java

对于for循环主体中的第一行,curr = arr [i],我的insertsort算法始终收到不兼容的类型错误。不确定如何解决此问题,我以为Comparable Object可与int配合使用。

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;
        }

    }

1 个答案:

答案 0 :(得分:0)

那么您有一个Comparable数组,并且希望可以将其分配给类型为curr的{​​{1}}。您如何期望int类型的对象神奇地成为整数?

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