Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在插入排序中使用replace()使语句不必要_C++_Algorithm_Sorting_Insertion Sort - Fatal编程技术网

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

C++ 如何在插入排序中使用replace()使语句不必要,c++,algorithm,sorting,insertion-sort,C++,Algorithm,Sorting,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

我希望有人能帮我完成这项任务。因此,我们的教授得到了这个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;
  }
}
template//由类型T参数化
void insertion\u sort(array&A)//A是Ts的数组
//将元素按升序排序
//假设A的下界为1
{int n=A.size();
对于(int k=2;k=1&&x=1
{A[i+1]=A[i];
我--;
}
A[i+1]=x;
}
}
好的,现在我必须在第5行和第6行之间使用函数A.resize(0,n),以便语句“I>=1”在while中,函数变得不必要。我知道,当使用此函数时,A的索引下界将变为0而不是1。但我看不到它有任何用处,因为我在while中仍然需要该语句。有人有想法吗

我将非常感激


提前谢谢!

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

如果严格需要使用
调整大小
,则只需将可能的最小值(查看)设置为具有第0个索引的新元素


我们无法从一些库中了解“魔法”例程,这将是一个相当大的技巧,因为没有调整大小的方法。我的教授说他使用名为“Leda”的库来实现此函数。但这不是排序算法,因为我不知道数组中最小的数组元素在哪里。a.resize(0,n)在数组的开头添加一个额外的未知元素,而不更改其他元素的索引。您可以进行第一次遍历以找到最小的元素。如果严格需要使用
调整大小
,则只需将可能的最小值(-infinity,-MAXINT等)设置为具有第0个索引的新元素。