天天看点

02、数据结构和算法--算法分析

算法分析

有关算法时间耗费分析,我们称之为算法的时间复杂度分析,有关算法的空间耗费分析,我们称之为算法的空间复杂度分析。

时间复杂度分析

我们要计算算法时间耗费情况,首先我们得度量算法的执行时间,有两种方法:

事后分析估算法

事前分析估算法

这种统计方法主要是通过设计好的测试程序和测试数据,利用计算机计时器对不同的算法编制的程序的运行时间进行比较,从而确定算法效率的高低。

这种方法有很大缺陷,必须依靠算法实现编制好的程序外,不同的测试环境导致测试结果差异很大。

public class TestDemo {
    public static void main(String[] args){
        long start = System.currentTimeMillis();
        int sum = 0;
        int n = 100;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("sum=" + sum);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
           

在计算机程序编写前,依据统计方法对算法进行估算,经过总结,我们发现一个高级语言编写的程序程序在计算机上运行所消耗的时间取决于下列因素:

1、算法采用的策略和方案;

2、编译产生的代码质量;

3、问题的输入规模(所谓的问题输入规模就是输入量的多少);

4、机器执行指令的速度;

一个程序的运行时间依赖于算法的好坏和问题的输入规模。

比如我们之前计算1到100的和的程序一样,有两种解法:

// 第一种解法,输入量为1则需要计算1次,计算次数会随着输入量而增大
public static void main(String[] args){
    int sum = 0;
    int n = 100;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    System.out.println("sum=" + sum);
}

// 第二种解法,输入量为1或N都只会计算一次
public static void main(String[] args){
    int sum = 0;
    int n = 100;
    sum = (n + 1) * n / 2;
    System.out.println("sum=" + sum);
}
           

我们分析一个算法的运行时间,最重要的就是把核心操作的次数和输入规模关联起来。

02、数据结构和算法--算法分析

函数近似增长

给定两个函数f(n)和g(n),如果存在一个整数N,使得对于所有的n>N,f(n)总是比g(n)大,那么我们说f(n)的增长渐近快于g(n)。

假设四个算法的输入规模都是n:

1、算法A1要做2n+3次操作:先执行n次循环,执行完毕后,再有一个n次循环,最后有3次运算;

2、算法A2要做2n次操作;

3、算法B1要做3n+1次操作:先执行n次循环,再执行一个n次循环,再执行一个n次循环,最后有1次运算。

4、算法B2要做3n次操作;

运算如下表所示:

输入规模 算法A1(2n+3)执行次数 算法A2(2n)执行次数 算法B1(3n+1)执行次数 算法B2(3n)执行次数
n = 1 5 2 4 3
n = 2 7 6
n = 3 10 9
n = 10 23 20 31 30
n = 100 203 200 301 300

从表中我们可以得出如下结论:

当输入规模n>2时,算法A1的渐近增长小于算法B1 的渐近增长

其中,折线图如下所示:

02、数据结构和算法--算法分析

通过观察折线图,我们发现,随着输入规模的增大,算法A1和算法A2逐渐重叠到一块,算法B1和算法B2逐渐重叠到一块,所以我们得出结论:

随着输入规模的增大,算法的常数操作可以忽略不计

算法时间复杂度

算法的时间复杂度,就是算法的时间量度,记作:

T(n)=O(f(n))

它表示随着问题规模n的增大,算法执行时间的增长率和f(n)的增长率相同,称作算法的渐近时间复杂度,简称时间复杂度。

用大写O()来体现算法时间复杂度的记法,我们称之为大O记法。一般情况下,随着输入规模n的增大,T(n)增长最慢的算法为最优算法。

下面我们使用大O表示法来表示一些求和算法的时间复杂度:

算法一:

public class TestDemo {
    public static void main(String[] args) {
        int sum = 0;	// 执行1次
        int n = 100;	//执行1次
        sum = (n + 1) * n / 2;	// 执行1次  
        System.out.println("sum= " + sum);
    }
}
           

算法二:

public class TestDemo {
    public static void main(String[] args){
        int sum = 0; // 执行1次
        int n = 100; // 执行1次
        for (int i = 1; i <= n; i++) {
            sum += i;   // 执行n次
        }
        System.out.println("sum= " + sum);
    }
}
           

算法三:

public class TestDemo {
    public static void main(String[] args){
        int sum = 0; // 执行1次
        int n = 100; // 执行1次
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sum += i;   // 执行n ^ 2次
            }
        }
        System.out.println("sum= " + sum);
    }
}
           

如果忽略判断条件的执行次数和输出语句的执行次数,那么当输入规模为n时,以上算法执行的次数分别为:

算法一:3次

算法二:n + 3次

算法三:n^2 + 2次

基于我们对函数渐近增长的分析,推导大O阶的表示法有以下几个规则可以使用:

1、用常数1取代运行时间中的所有加法常数;

2、在修改后的运行次数中,只保留高阶项;

3、如果最高阶项存在,且常数因子不为1,则去除与这个项相乘的常数;

所以,上述算法的大O记法分别为:

算法一:O(1)

算法二:O(n)

算法三:O(n^2)

常见大O阶

1、线性阶:一般含有非嵌套循环涉及线性阶,线性阶就是随着输入规模的扩大,对应计算次数呈直线增长,例如:

public class TestDemo {
    public static void main(String[] args){
        int sum = 0;
        int n = 100;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("sum= " + sum);
    }
}
           

上面这段代码,它的循环的时间复杂度为O(n),因为循环体中的代码需要执行n次。

2、平方阶:一般嵌套循环属于这种时间复杂度

public class TestDemo {
    public static void main(String[] args){
        int sum = 0;
        int n = 100;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sum += i;
            }
        }
        System.out.println(sum);
    }
}
           

总共程序想要从这两个循环中出来,就需要执行100*100次,也就是n的平方次,时间复杂度是O(\(n^2\))。

3、立方阶:一般三层嵌套循环属于这种时间复杂度

public class TestDemo {
    public static void main(String[] args){
        int x = 0;
        int n = 100;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                for (int k = 1; k <= n; k++) {
                    x++;
                }
            }
        }
        System.out.println(x);
    }
}
           

总共程序想要从这三个循环中出来,就需要执行1000000次,也就是n的立方,的时间复杂度是O(\(n^3\))。

4、对数阶:在数学中,对数是对求幂的逆运算,正如除法是乘法的倒数,反之亦然。

public class TestDemo {
    public static void main(String[] args){
        int i = 1, n = 100;
        while (i < n){
            i = i * 2;
        }
    }
}
           

由于是2^x=n,得到x = \(log_2n\),所以这个循环的时间复杂度为O(\(log_n\));

5、常数阶:一般不涉及循环操作的都是常数阶,因为它不会随着n的增长而增加操作次数。

public class TestDemo {
    public static void main(String[] args){
        int  n = 100;
        int i = n + 2;
        System.out.println(i);
    }
}
           

不管输入规模n是多少,都执行2次,根据大O推导法则,常数用1来替换,所以时间复杂度为O(1)。

下面是对常见时间复杂度的一个总结:

描述 增长的数量级 说明 举例
常数级别 1 普通语句 将两个数相加
对数级别 logN 二分策略 二分查找
线性级别 N 循环 找出最大元素
线性对数级别 NlogN 分治思想 归并排序
平方级别 \(N ^ 2\) 双层循环 检查所有元素对
立方级别 \(N ^ 3\) 三层循环 检查所有三元组
指数级别 \(2 ^ N\) 穷举查找 检查所有子集

他们的复杂程度从低到高依次为:

O(1) < O(logn) < O(n) < O(nlogn) < O(\(n^2\))<O(\(n^3\))

从平方阶开始,随着输入规模的增大,时间成本会急剧增大,所以,我们的算法,尽可能的追求的是O(1)、O(logn)、O(n)、O(nlogn)这几种时间复杂度,而如果发现算法的时间复杂度为平方阶、立方阶或者更复杂的,那我们可以分为这种算法是不可取的,需要优化。

函数调用的时间复杂度

接下来我们分析函数调用过程中时间复杂度。

案例一:

public class TestDemo {
    public static void main(String[] args){
        int  n = 100;
        for (int i = 0; i < n; i++) {
            show(i);
        }
    }

    private static void show(int i){
        System.out.println(i);
    }
}
           

show方法内部只执行了一行代码,所以show方法的时间复杂度为O(1),那main方法的时间复杂度就是O(n)。

案例二:

public class TestDemo {
    public static void main(String[] args){
        int  n = 100;
        for (int i = 0; i < n; i++) {
            show(i);
        }
    }

    private static void show(int i){
        for (int j = 0; j < i; j++) {
            System.out.println(i);
        }
    }
}
           

show方法内部也有一个for循环,所以show方法的时间复杂度为O(n),那main方法的时间复杂度为O(\(n^2\))。

案例三:

public class TestDemo {
    public static void main(String[] args){
        int  n = 100;
        show(n);
        for (int i = 0; i < n; i++) {
            show(i);
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.println(j);
            }
        }
    }

    private static void show(int i){
        for (int j = 0; j < i; j++) {
            System.out.println(i);
        }
    }
}
           

在show方法中,有一个for循环,所以show方法的时间复杂度为O(n),main方法总执行次数为:

n + \(n^2\) + n\(^2\) = 2\(n^2\) + n

根据大O推导规则,去掉n保留最高阶项,并去掉最高阶项的常数因子2,所以最终main方法的时间复杂度为O(\(n^2\));

算法的空间复杂度分析

算法的空间复杂度

算法的空间复杂度计算公式记作:S(n)=O(f(n)),其中n为输入规模,f(n)为语句关于n所占存储空间的函数。

对指定的数组元素进行反转,并返回反转的内容。

方式一:

public static int[] reverse(int[] arr){
    int n = arr.length;
    int temp;
    for (int start = 0, end = n - 1; start <= end; start++, end--){
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
    }
    return arr;
}
           

方式二:

public static int[] reverse(int[] arr){
    int n = arr.length;
    int[] temp = new int[n];	// //申请n * 4个字节 + 数组自身头信息开销24个字节
    for (int i = n - 1; i >= 0 ; i--) {
        temp[n - 1 - i] = arr[i];
    }
    return temp;
}
           

忽略判断条件占用的内存,我们得出的内存占用情况如下: