简体   繁体   English

冒泡排序算法。 最坏情况下的时间复杂度是多少?

[英]Bubblesort-like algorithm. What is the worst-case time complexity?

I made a sorting algorithm using the same kind of logic of the heapify algorithm.我使用与 heapify 算法相同的逻辑制作了一个排序算法。 However, I do not believe this is heap sort.但是,我不相信这是堆排序。 The logic of it, is that I compare two pieces of an array (Initially was going to be a double linked list, but java would not allow me to do that without making my own class) with the one next to it.它的逻辑是,我将数组的两个部分(最初将是一个双链表,但 java 不允许我在不创建自己的类的情况下这样做)与它旁边的一个进行比较。 If it is larger, swap.如果它更大,请交换。 Much like a bubble sort.很像冒泡排序。 However, when the swap is completed, I then do a reverse bubble sort on the second element, to maintain the order of the array.但是,当交换完成后,我会对第二个元素进行反向冒泡排序,以保持数组的顺序。

I'm not entirely sure of the worst case time complexity of this, but I think it is O(n^2).我不完全确定最坏情况的时间复杂度,但我认为它是 O(n^2)。 What is the time complexity of this, and also, what sorting algorithm does it most look like?这个的时间复杂度是多少,以及它最像什么排序算法?

import java.util.Arrays;

/**
 * firstNum and secondNum trade places.
 * Whenever a swap is done, sink the secondNumber
 */
private static void swap(int[] A, int firstNum, int secondNum) {
    int temp = A[secondNum];

    A[secondNum] = A[firstNum];
    A[firstNum] = temp;

    sink(A, firstNum);
}

/**
 * Swap places upward until condition is false.
 */
private static void rise(int[] A, int currIndex) {

    int nextIndex = currIndex + 1;

    if (nextIndex <= A.length - 1 && A[currIndex] > A[nextIndex]) {

        swap(A, currIndex, nextIndex);
        rise(A, nextIndex);
    }
}

/**
 * Swap places downward until condition is not met.
 */
private static void sink(int[] A, int currIndex) {

    int prevIndex = currIndex - 1;

    if (currIndex > 0 &&  A[currIndex] < A[currIndex - 1]) {
        swap(A, prevIndex, currIndex);
    }
}

public static void main(String[] args) {

    int[] values = {4, 7, 2, 1, 3, 5, 100, 0};

    for (int i = 0; i < values.length - 1; i++) {
        rise(values, i);
    }

    System.out.println(Arrays.toString(values));


}

} }

I'd say this is insertion sort in disguise.我会说这是变相的插入排序。 It thus has worst case and average complexity of O(n^2).因此,它具有 O(n^2) 的最坏情况和平均复杂度。

To see this, first realize that the recursive call to rise in the rise method is redundant: the element being raised there will be reached anyway by a later call to rise from the outer loop in the main method.要看到这一点,首先要意识到在rise方法中对rise的递归调用是多余的:无论如何,在main方法中从外部循环调用rise将到达那里被引发的元素。 What's left is recursive calls to sink from the swap method for every element in the list.剩下的就是从列表中的每个元素的swap方法中递归调用sink What that does is to place every element into the right position in the already sorted initial bit of the list: this is essentially insertion sort.这样做是将每个元素放入列表中已经排序的初始位的右侧 position 中:这本质上是插入排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM