【发布时间】:2018-03-27 05:17:32
【问题描述】:
嘿,伙计们,我明天有一个测验,我在寻找选择排序的递归程序的时间复杂度时遇到了一些问题,任何人都可以解释它是如何 n^2 的。还有一个问题,一些排序算法循环的时间复杂度为 n/2,对于新手问题,/2 是什么意思?
#include <iostream>
using namespace std;
// recursive function to perform selection sort on subarray arr[i..n-1]
void selectionSort(int arr[], int i, int n)
{
// find the minimum element in the unsorted subarray[i..n-1]
// and swap it with arr[i]
int min = i;
for (int j = i + 1; j < n; j++)
{
// if arr[j] element is less, then it is the new minimum
if (arr[j] < arr[min])
min = j; // update index of min element
}
// swap the minimum element in subarray[i..n-1] with arr[i]
swap(arr[min], arr[i]);
if (i + 1 < n)
selectionSort(arr, i + 1, n);
}
【问题讨论】:
-
selectionSort(arr, 0, n)将在其循环中进行n比较。然后它会调用selectionSort(arr, 1, n)来进行额外的n-1比较,并调用selectionSort(arr, 2, n)来进行更多n-2比较,依此类推。我们将计算这个算术级数的总和留给读者作为练习。 -
n/2的复杂性毫无意义,因为大 O 符号与常数乘数无关。O(n/2) == O(n) -
在选择排序的迭代算法中有一个值 n/2(n-1) 这是什么意思谢谢你@IgorTandetnik
标签: c++ algorithm recursion data-structures