【问题标题】:Trying to understand the Binary Insertion Sort?试图理解二进制插入排序?
【发布时间】:2023-03-10 08:50:01
【问题描述】:

谁能告诉我这段代码如何对数组进行排序?我不明白!这段代码如何降低常规插入排序的复杂性?

// Function to sort an array a[] of size 'n'
void insertionSort(int a[], int n)
{
    int i, loc, j, k, selected;

    for (i = 1; i < n; ++i)
    {
        j = i - 1;
        selected = a[i];

        // find location where selected sould be inseretd
        loc = binarySearch(a, selected, 0, j);

        // Move all elements after location to create space
        while (j >= loc)
        {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = selected;
    }
}

【问题讨论】:

标签: c++ algorithm sorting binary-search


【解决方案1】:

此代码使用的事实是,数组中从零(包括)到 i(不包括)的部分已经排序。这就是为什么它可以为a[i]的插入位置运行binarySearch,而不是线性搜索它。

这个聪明的技巧不会改变算法的渐近复杂度,因为从loci 的元素移动的部分保持线性。在最坏的情况下(当数组反向排序时发生)每个N 插入步骤都会使i 移动,总共移动N(N-1)/2 次。

与经典插入排序相比,该算法的唯一改进是比较次数。如果正在排序的对象的比较计算量很大,则此算法可以显着降低常数因子。

【讨论】:

  • 好吧,如果您的数据结构不是数组/列表,而是例如跳过列表,那么二进制搜索将使您的复杂度为 O(n * log(n)),因为插入/删除将是恒定的并且二进制搜索将是 O(log(n))
猜你喜欢
  • 2023-03-07
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
相关资源
最近更新 更多