You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C语言插入排序代码,输出带循环索引前缀的每轮排序状态?

代码修改方案

你只需调整insertionSort函数中的打印逻辑即可:前缀打印语句要放在每轮排序结束后、遍历打印数组之前,使用外层循环的变量i作为索引值,不要放在遍历数组的内层循环中。

修改后的完整代码

#include <stdio.h>

void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;

        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;

        // 先打印前缀,索引用当前外层循环的i值
        printf("Loop is at index = %d. Sorting in progress:  [", i);
        // 打印数组,调整格式和Python版本对齐
        for (j = 0; j < n; j++){
            printf("%d", arr[j]);
            if(j != n - 1)
                printf(", ");
        }
        printf("]\n");
    }
}

void printArray(int arr[], int n)
{
    int i;
    printf("[");
    for (i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if (i != n - 1)
            printf(", ");
    }
    printf("]\n");
}

int main()
{
    int arr[] = {6, 5, 4, 3, 7, 1, 2};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("\nOriginal array: ");
    printArray(arr, n);

    printf("\nSorting in progress: \n\n");
    insertionSort(arr, n);
    printf("\n");

    printf("Sorted array: ");
    printArray(arr, n);

    return 0;
}

运行输出效果

Original array: [6, 5, 4, 3, 7, 1, 2]

Sorting in progress: 

Loop is at index = 1. Sorting in progress:  [5, 6, 4, 3, 7, 1, 2]
Loop is at index = 2. Sorting in progress:  [4, 5, 6, 3, 7, 1, 2]
Loop is at index = 3. Sorting in progress:  [3, 4, 5, 6, 7, 1, 2]
Loop is at index = 4. Sorting in progress:  [3, 4, 5, 6, 7, 1, 2]
Loop is at index = 5. Sorting in progress:  [1, 3, 4, 5, 6, 7, 2]
Loop is at index = 6. Sorting in progress:  [1, 2, 3, 4, 5, 6, 7]


Sorted array: [1, 2, 3, 4, 5, 6, 7]

如果你不需要完全对齐Python的数组方括号格式,只需要加前缀的话,仅需把前缀打印放在遍历数组的循环之前即可,无需修改数组打印逻辑。


内容的提问来源于stack exchange,提问作者Suswagatam Rong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:36:03