Java 寻找大O递归

Java 寻找大O递归,java,time-complexity,space-complexity,Java,Time Complexity,Space Complexity,我试图从下面的代码中找出什么是大O和大Omega 这段代码输入一个整数数组,并按升序对它们进行排序。 最坏的情况是所有这些都按降序{5,4,3,2,1} ,最好的情况是升序{1,2,3,4,5} static int counter = 0; static int counter1 = 0; static int counter2 = 0; public static int[] MyAlgorithm(int[]a) { int n = a.length; boolean d

我试图从下面的代码中找出什么是大O和大Omega

这段代码输入一个整数数组,并按升序对它们进行排序。 最坏的情况是所有这些都按降序{5,4,3,2,1} ,最好的情况是升序{1,2,3,4,5}

static int counter = 0;
static int counter1 = 0;
static int counter2 = 0;

public static int[] MyAlgorithm(int[]a) {
    int n = a.length;
    boolean done = true;
    int j = 0;
    while(j<=n-2) {
        counter++;
        if(a[j]>a[j+1]) {
            int temp = a[j];
            a[j] = a[j+1];
            a[j+1] = temp;
            done = false;
        }
        j = j+1;
    }
    j = n-1;
    while(j>=1) {
        counter1++;
        if(a[j]<a[j-1]) {
            int temp = a[j-1];
            a[j-1] = a[j];
            a[j] = temp;
            done = false;
        }
        j = j-1;
    }
    if(!done) {
        counter2++;
        MyAlgorithm(a);
    }
    return a;

}
静态整数计数器=0;
静态int计数器1=0;
静态int计数器2=0;
公共静态int[]MyAlgorithm(int[]a){
int n=a.长度;
布尔完成=真;
int j=0;
而(ja[j+1]){
内部温度=a[j];
a[j]=a[j+1];
a[j+1]=温度;
完成=错误;
}
j=j+1;
}
j=n-1;
而(j>=1){
计数器1++;

如果(a[j]如您所说,ω是
Omega(n)
。如果数组
a
中的所有数字都已按排序顺序排列,则代码在数组上迭代两次,每次循环一次。这是
n
步骤
O(1)

在最坏的情况下,假设
O(n^2)是正确的
。正如您所看到的,按相反顺序排序的数组会产生这样的最坏情况。我们也可以通过按递增顺序排序数组,然后只交换第一个和最后一个数字来产生最坏情况。然后每次运行
MyAlgorithm
都会将最后/第一个数字移动到两个位置。在
n/2
步骤之后(运行
MyAlgorithm
)数字到达其最终位置。因此,
O(n/2*n)=O(n^2)



小旁注,排序通常在
O(n log n)
中,因此您只能在
O(n)
中的某些情况下对某些内容进行排序。谢谢!我还可以说这是尾部递归吗?尾部递归意味着在隐式步骤中使用当前迭代的结果,这对于
MyAlgorithm
是正确的。