插入排序如何打印整个数组

时间:2014-09-02 00:23:16

标签: java sorting

我想知道如何在输出中显示插入排序的分步过程。如果我将20,5,9,8,7输出为5,7,8,9,20。它没有显示一步一步的过程,我该如何显示?这是我的代码:

for(i=0; i<r; i++) {
    System.out.print(data[i]+"\t");
}

System.out.print("\n");

for (j=1; j<r;j++) {
    temp = data[j];
    for( i=j-1; i>=0 && temp < data[i]; i--)
    data[i+1]= data[i];
    data[i+1]=temp;
}

for(j=0; j<r; j++) {
    System.out.print(data[j]+"\t");
    System.out.print("\n");
    break;
}

1 个答案:

答案 0 :(得分:1)

  

它没有显示一步一步的过程,我该如何显示?

我会使用Arrays.toString(int[])和格式化输出与printf(String, Object...)的组合。像,

public static void main(String[] args) {
    int[] data = { 20, 5, 9, 8, 7 };
    System.out.println("Before sort: " + Arrays.toString(data));
    sort(data);
    System.out.println("After sort: " + Arrays.toString(data));
}

public static void sort(int[] data) {
    int i;
    for (int j = 1, r = data.length; j < r; j++) {
        int temp = data[j];
        System.out.printf("Sorting %d from pos=%d%n", temp, j);
        for (i = j - 1; i >= 0 && temp < data[i]; i--) {
            data[i + 1] = data[i];
            System.out.printf("%d is less then %d, shifting up%n", tehmp,
                    data[i]);
        }
        System.out.printf("%d moved from pos=%d to pos=%d%n", temp, j,
                i + 1);
        data[i + 1] = temp;
        System.out.printf("After iteration %d: %s%n", j,
                Arrays.toString(data));
    }
}