如何在插入排序中使用 replace() 使语句变得不必要

How to make a statement unnecessary with replace() in insertion-sort

本文关键字:语句 不必要 插入排序 replace      更新时间:2023-10-16

我希望有人能帮我完成这个任务。所以我们得到了我的教授的这个C++算法:

template<class T> //Parameterized by the Type T
void insertion_sort(array<T>& A) //A is an array of Ts
//Permutes the elements of A into ascending sorted order
//The lower index bound of A is assumed to be 1
{ int n = A.size();
for(int k=2; k<=n; k++)
{ T x = A[k];   //x is a a variable of type T
//Insert x in the sorted sequence A[1], ..., A[k-1]
int i = k-1;
while (i>=1&&x<A[i])  //A[i] is evaluated only if i>=1
{ A[i+1]=A[i];
i--;
}
A[i+1]=x;
}
}

还行。现在我必须在第 5 行和第 6 行之间使用函数 A.resize(0, n(,以便 while 函数中的语句 "i>=1" 变得不必要。我知道当使用此函数时,A 的下限变为 0 而不是 1。但我看不出有什么用,因为我在一段时间内仍然需要这个声明。有人有想法吗?

我将不胜感激。

提前谢谢你!

要排除i>=1条件,您可以将最小的数组元素移动到主循环之前的第一个位置。
现在这个元素变成了"哨兵",它的存在排除了数组范围的用完。

如果严格需要使用您的resize,那么只需将尽可能小的值(查看最低值(设置为具有第 0 个索引的新元素。

我们无法从某些库中了解"魔术"例程