c - 插入排序进行到一半时打印数组的内容

标签 c arrays algorithm sorting

我写了一个简单的插入排序算法,它运行良好。我想要的是如果程序在排序一半时打印数组的内容。我可以很好地打印数组的内容,但我不知道如何判断数组何时排序一半。这是我的代码

void insertion_sort(int *a, int n) {

    /*initialise data field*/
    int p;/*position index*/
    int key;/*key item*/
    int i;/*index in array*/

    /*for position in array*/
    for (p=1; p<n; p++){
        key = a[p];
        i= p-1;

        /*while i is valid and a[i] is less then key, move the item forward one*/
        while (i >= 0 && a[i] > key){
            a[i+1]=a[i];
            i--;
        }/*end while*/

        a[i+1]= key;
    }/*end for*/  
}/*end insertion_sort*/

感谢任何帮助, 干杯!

最佳答案

之后

a[i+1]= key;

如果位置 p 等于数组大小的一半(n/2,如果 n 是偶数或 n/2 + 1 否则 - 在这种情况下你调用你定义为一半的东西),那么你的数组将是半排序的。

关于c - 插入排序进行到一半时打印数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46296683/

相关文章:

javascript - 如何计算数组中有多少个不同的对象?

c++ - 将字符串/ double vector 转换为数组

multithreading - 在线程池中分配工作负载的算法

algorithm - 寻找最低的平均等级差异

c - 逐行散列文件

C++ I/O 文件流相对于 C 语言的优势

C 将指向 char* 的指针设置为 char*

c++ - 在 Go 应用程序中使用 C(++) 提高性能

java - java创建数组的方法

arrays - Kotlin 中使用 For 循环将 Int 数组元素插入 String 列表的问题(使用了 toString)