如何在插入排序中使用 replace() 使语句变得不必要
How to make a statement unnecessary with replace() in insertion-sort
我希望有人能帮我完成这个任务。所以我们得到了我的教授的这个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 个索引的新元素。
我们无法从某些库中了解"魔术"例程
相关文章:
- 用callgrind追踪不必要的副本
- 不必要的C++代码最终会出现在我完成的程序中吗?
- 总和的不必要行为C++?
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- C++ 中的"if"语句不会从左到右计算条件
- 如果语句不包括文本行?
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 如果语句不会在 do - while 循环中运行
- 函数中的切换大小写语句不会切换C++
- std::mutex::lock() 产生奇怪(和不必要的)ASM 代码
- 如何在插入排序中使用 replace() 使语句变得不必要
- C++ 中断语句不起作用
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- C 包装器C++库周围没有不必要的头文件
- 编译器是否消除了不必要的原子?
- 在 c++ 中不必要的包含
- 案例语句不会前进到下一个语句
- 不必要的 else 语句:当可以使用 IF 时,使用 ELSE IF 有什么缺点吗?
- 函数中不必要的弹出指令,前面有if语句