程序的大O符号(最坏情况)

时间:2014-09-28 21:41:22

标签: java big-o complexity-theory

我对复杂性理论有疑问。如果我有一个冒泡排序算法,并且我想找到最坏的情况下运行时间Big O,我们可以得出结论它是O(n ^ 2)。现在,如果我有一个执行不同操作的程序,如排序算法,搜索算法等等。我怎么知道这个程序的最坏情况运行时间(Big O)是什么。

例如,如何在程序中使用不同的算法及其各自的最坏情况运行时间Big O表示法得出整个程序的最坏情况运行时间(Big O)的结论。就像程序具有以下内容:O(n ^ 2),O(1),O(n)....这些符号中的哪一个是代表整个程序的符号?

你怎么能找到这个程序最糟糕的运行时间Big O?

import java.util.*;
public class Prog1 {
   public static void main(String[] args) {

    int first = 0;
    int last;
    int middle;
    int search;
    int[] array;

    Scanner input = new Scanner(System.in);
    System.out.println("Number of elements");
    int n = input.nextInt();

    array = new int[n];

    System.out.println("Enter " + n + " value ");
    for (int x = 0; x < n; x++) {
        array[x] = input.nextInt();
    }

    System.out.println("Value to search");
    search = input.nextInt();

    last = n - 1;
    middle = (first + last) / 2;

    while (first <= last) {
        if (array[middle] < search)
            first = middle + 1;
        else if (array[middle] == search) {
            System.out.println(" Number " + search + " is in the array");
            break;
        } else
            last = middle - 1;

        middle = (first + last) / 2;
    }
    if (first > last)
        System.out.println(" Number " + search + " is not in the list.");
 }
}

1 个答案:

答案 0 :(得分:3)

最高的一个。 O(n ^ 2)+ O(n)+ O(1)= O(n ^ 2)渐近说话! 这就是你如何计算算法的复杂性。 谈论程序“复杂性”没有多大意义。