Algorithm 选择排序的复杂性分析

Algorithm 选择排序的复杂性分析,algorithm,complexity-theory,Algorithm,Complexity Theory,这是我写的一个SelectionSort例程。我接下来的复杂性分析正确吗 public static void selectionSort(int[] numbers) { // Iterate over each cell starting from the last one and working backwards for (int i = numbers.length - 1; i >=1; i--) { // Always set the

这是我写的一个SelectionSort例程。我接下来的复杂性分析正确吗

public static void selectionSort(int[] numbers) {

    // Iterate over each cell starting from the last one and working backwards
    for (int i = numbers.length - 1; i >=1; i--)
    {
        // Always set the max pos to 0 at the start of each iteration
        int maxPos = 0;

        // Start at cell 1 and iterate up to the second last cell
        for (int j = 1; j < i; j++)
        {
            // If the number in the current cell is larger than the one in maxPos,
            // set a new maxPos
            if (numbers[j] > numbers[maxPos])
            {
                maxPos = j;
            }
        }

        // We now have the position of the maximum number. If the maximum number is greater
        // than the number in the current cell swap them
        if (numbers[maxPos] > numbers[i])
        {
            int temp = numbers[i];
            numbers[i] = numbers[maxPos];
            numbers[maxPos] = temp;
        }
    }
}
publicstaticvoidselectionsort(int[]数字){
//从最后一个单元格开始,向后遍历每个单元格
对于(int i=numbers.length-1;i>=1;i--)
{
//每次迭代开始时,始终将最大位置设置为0
int-maxPos=0;
//从单元格1开始,迭代到最后一个单元格
对于(int j=1;j数字[maxPos])
{
maxPos=j;
}
}
//我们现在有了最大数的位置。如果最大数大于
//比当前单元格中的数字要多,请将其交换
if(数字[maxPos]>数字[i])
{
int temp=数字[i];
数字[i]=数字[maxPos];
数字[maxPos]=温度;
}
}
}
复杂性分析

输出环路(比较和分配):执行2次运算n次=2n次运算

分配maxPos:n操作

内部循环(比较和分配):执行2次运算2n^2次=2n²运算

数组元素比较(两个数组引用和一个比较):3n²ops

分配新的maxPos:n²ops

数组元素比较(两个数组引用和一个比较):3n²ops

分配和阵列参考:2n²操作

分配和2个阵列引用:3n²操作

分配和阵列参考:2n²操作

基本操作的总数

2n+n+2n²+3n²+n^2+3n²+2n²+3n²+2n²=16n²+3n²

通向大Oh(n²)

看起来对吗?特别是当涉及到内部循环和其中的内容时…

是的,O(N2)是正确的

编辑:就“从第一原理”而言,很难猜测他们到底想要什么,但我猜他们(本质上)是在寻找符合大O基本定义的证据(或至少是迹象):

存在正常数cn0,因此:

0≤ f(n)≤ 所有n的cg(n)≥ 不

因此,找到16N2+3N后的下一步是找到n0和c的正确值。至少乍一看,c似乎是16,n0,-3(可能被视为0,元素的负数没有实际意义)。

通常,将实际操作相加是毫无意义的(也是不正确的),因为操作需要不同数量的处理器周期,它们中的一些会从内存中取消引用值,这需要花费更多的时间,然后它会变得更加复杂,因为编译器会优化代码,然后你会有缓存局部性之类的东西,所以除非你真的、真的很好地知道下面的一切是如何工作的,否则你就是在积少成多。你不能把“j
复杂度确实是N^2,但是你的系数是没有意义的。

但是我想知道我的推导是否正确?这是从第一原理进行复杂性分析的正确方法吗?@Jim_CS:值得商榷。大多数人通常从基本上消除常数复杂度操作开始,因此他们从不真正考虑赋值、比较等的确切数量,本质上说:“f(N)常数复杂度操作,因此O(f(N))”.我要参加考试,在过去的试卷中,有时它要求我们推导出一个O-符号复杂度函数算法,有时它特别要求从“第一原理”推导出各种排序算法的复杂度。所以我假设“第一原理”在这里意味着原始操作?我知道,我在谈论一个“简单完美世界”的场景,在这个场景中,所有原始操作都是相等的,这就像将它们相加一样简单。在这种情况下,我认为共同效率是有意义的。我知道这在实践中不是那么简单,但这必须为考试做。