【问题标题】:Print contents of array, when half way through insertion sort在插入排序进行到一半时打印数组的内容
【发布时间】:2017-09-19 09:25:51
【问题描述】:

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

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(可能使用一些“地板”或“天花板”函数?)你的数组应该是半排序的。
  • “半排序”到底是什么意思?可以有多种解释。

标签: c arrays algorithm sorting


【解决方案1】:

之后

a[i+1]= key;

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

【讨论】:

    猜你喜欢
    • 2011-11-28
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2019-07-15
    • 2016-05-05
    相关资源
    最近更新 更多