无法获得正确数量的插入排序键比较

时间:2017-10-19 00:19:13

标签: java algorithm sorting

我正在努力解决插入排序键比较和交换计数的问题。

我有这种方法可以计算并打印出最后的密钥比较

public static void insertionSort(int[] array) {

    int n = array.length;
    int cm = 0;
    int sw = 0;


    for (int pass = 0; pass < array.length; pass++) {
        // figure out what should go into a[pass]
        int min = pass;
        for (int j = pass + 1; j < array.length; j++) {
            if (smaller(array, j, min)) {
                cm++;
                min = j;
            }
        }
        swap(array, pass, min);
        sw++;
    }

    System.out.print("Insertion sort: ");
    for (int c = 0; c < n; c++) {
        System.out.print(array[c] + " ");


    }

    System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}

private static void swap(int[] a, int i, int j) {
    if (i != j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

private static boolean smaller(int[] a, int i, int j) {
    //another suggestion came up to call a count variable here because a false comparison could still count as a comparison
    count++;
    if (a[i] < a[j]) {
        return true;
    }
    return false;
}

使用此测试数组

int[] test = {13, 12, 5, 6, 11};

我应该进行 7 比较和 4 掉期,但我正在进行 5 比较和 5 掉期。 使用从 0 31 的另一个数组(测试最佳情况), 我得到 0 比较和 32 交换。

1 个答案:

答案 0 :(得分:0)

更新答案。 这适用于比较计数,但仍然可以处理交换计数。

private static int COMPCOUNT = 0;
public static void main(String[] args) {
    //best case for insertion sort is increasing order
    int[] bestCase = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
    //the worst case for insertion sort is decreasing order;
    int[] worstCase = {31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

    int[] randomArray = new int[32];
    for (int i = 0; i < randomArray.length; i++) {
        randomArray[i] = genarateRandom(32);
    }
}

public static int genarateRandom(int bound) {
    Random random = new Random();
    int rand = random.nextInt(bound);
    return rand;
}

private static boolean smaller(int[] a, int i, int j) {
    if (a[i] < a[j]) {
        COMPCOUNT++;
        return true;
    }
    return false;
}


public static void insertionSort(int[] arr)
{
    COMPCOUNT=0;
    int temp;
    for (int i = 1; i < arr.length; i++) {
        for(int j = i ; j > 0 ; j--){
            //use boolean function to check A[i] < A[j]
            if(smaller(arr, j, j-1)){
                //swap
                temp = arr[j];
                arr[j] = arr[j-1];
                arr[j-1] = temp;
            }
        }
    }

    //print out the array
    System.out.print("Insertion sort: ");
    for (int c = 0; c < arr.length; c++) {
        System.out.print(arr[c] + " ");

    }

    //print out the number of comparison
    System.out.println("- " + COMPCOUNT + " comparisons");
}
相关问题