c++ - shell 排序中的交换和比较

标签 c++ sorting

我试图弄清楚如何找到 shell 排序函数中使用的交换和比较的总量,但我不太确定在哪里放置交换和比较的添加。

我在下面的这个 insertionSort 函数中添加了一些内容。

void insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
    int i = 0;
    int j = 0;
    int temp = 0;

    for (i = startIndex + gap; i < numbersSize; i += gap) {
        j = i;
        while (j - gap >= startIndex && numbers[j] < numbers[j - 1]) {
            temp = numbers[j];
            numbers[j] = numbers[j - gap];
            numbers[j - gap] = temp;
            j = j - gap;
            totalComps++; //declared globally
            totalSwaps++; //declared globally
        }

    }
}

我知道 totalSwaps 就在它所在的位置很好,但我不太确定将 totalComps 放在哪里,因为我们也在 while 循环中进行比较。

最佳答案

您可以使用一对 function objects ,一个进行比较,另一个进行交换。

struct counted_less
{
    int count = 0;
    bool operator()(int lhs, int rhs)
    {
        ++count;
        return lhs < rhs;
    }
}

struct counted_swap
{
    int count = 0;
    void operator()(int & lhs, int & rhs)
    {
        ++count;
        using std::swap;
        swap(lhs, rhs);
    }
}


std::pair<int, int> insertionSortInterleaved(int numbers[], int numbersSize, int startIndex, int gap) {
    counted_less less;
    counted_swap swap;

    for (int i = startIndex + gap; i < numbersSize; i += gap) {
        for (int j = i; j - gap >= startIndex && less(numbers[j], numbers[j - 1]); j -= gap) {
            swap(numbers[j], numbers[j - gap]);
        }
    }

    return { less.count, swap.count };
}

关于c++ - shell 排序中的交换和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048079/

相关文章:

c++ - 编写 CUDA 内核以替换等效的仅 CPU 函数

c++ - 在 C++ 中使用 STL 从上到下然后从左到右对 Vector<Points> 进行排序

python - 使用 numpy.argpartition 忽略 NaN

c++ - 字符串选择排序 C++

javascript - 对象数组不按属性排序

c++ - sqlite blob(由 c/c++ 数组组成)是否与平台无关?

c++ - 从文件输入 C++ 定义全局变量

c++ - 派生类C++访问派生类的基类

swift - 将 nil 日期排序到数组的末尾

arrays - 如何在 Perl 中按列对数组或表进行排序?