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