移动和键比较在 C++ 中是什么意思

What do move and key comparison mean in c++?

本文关键字:是什么 意思 C++ 比较 移动      更新时间:2023-10-16
以下是

在我的类中关于插入排序的ppt中写的:

void insertionSort(DataType theArray[], int n) {
  for (int unsorted = 1; unsorted < n; ++unsorted) {
    DataType nextItem = theArray[unsorted];
    int loc = unsorted;
    for (;(loc > 0) && (theArray[loc-1] > nextItem); --loc)
       theArray[loc] = theArray[loc-1];
    theArray[loc] = nextItem;
  }
}

-

Running time depends on not only the size of the array but also the contents of the array.
Best-case:       O(n)
Array is already sorted in ascending order.
Inner loop will not be executed.
>>>> The number of moves: 2*(n-1)        O(n)
>>>> The number of key comparisons: (n-1)    O(n)
Worst-case:      O(n2)
Array is in reverse order:
Inner loop is executed p-1 times, for p = 2,3, …, n
The number of moves: 2*(n-1)+(1+2+...+n-1)= 2*(n-1)+ n*(n-1)/2   O(n2)
The number of key comparisons: (1+2+...+n-1)= n*(n-1)/2          O(n2)
Average-case:    O(n2)
We have to look at all possible initial data organizations.
So, Insertion Sort is O(n2)

移动和关键比较到底是什么?我在谷歌上找不到解释。

让我先说一下算法。

  • 假设在给定时间数组有两个部分。 索引0到索引 loc - 1按升序排序,索引locn - 1不排序。
  • loc 处的元素开始,在数组的排序部分找到它的正确位置并将其插入其中。

所以现在有两个循环:

  1. 第一个外循环,从loc = 1loc = n开始,基本上将数组划分为已排序和未排序部分。
  2. 第二个内部循环在数组的排序部分(0loc - 1)中查找元素在loc的位置。

对于内部循环,要找到正确的位置,您必须将 loc 处的元素与数组排序部分中的所有元素进行比较,在最坏的情况下。这是关键的比较。

要插入,您必须在数组的排序部分中为 loc 处的元素创建一个空隙。这是通过将排序部分中的每个元素交换到下一个元素来完成的。这是感动。

Move 是

它为了对数据进行排序而必须执行的交换次数,键是要执行的数据。