我尝试编写一个插入排序函数,该函数将根据其参数 ( order
) 的符号在升序和降序之间切换。它可以工作,但看起来不正确,因为我用作开关的条件运算符会给内部循环的每次迭代增加一些开销。因此,我想就如何编写更好的函数版本征求您的意见。
void Array::sort(int order) //Array is a struct that contains a vector of pointers named vect, as well as this function.
{
if (order==0) return;
bool ascending = (order>0);
int i,j;
Data* buffer; //Data is a struct containing some variables, including the key that has to be sorted.
for (i=1; i<_size; i++)
{
buffer = vect[i]; //A vector of pointers to Data objects declared in the Array struct.
j=i-1;
while ( j>=0 && (ascending?(vect[j]->key > buffer->key):(vect[j]->key < buffer->key)))
{
vect[j+1] = vect[j];
j--;
}
vect[++j] = buffer;
}
}