[英]Bubblesort-like algorithm. What is the worst-case time complexity?
我使用與 heapify 算法相同的邏輯制作了一個排序算法。 但是,我不相信這是堆排序。 它的邏輯是,我將數組的兩個部分(最初將是一個雙鏈表,但 java 不允許我在不創建自己的類的情況下這樣做)與它旁邊的一個進行比較。 如果它更大,請交換。 很像冒泡排序。 但是,當交換完成后,我會對第二個元素進行反向冒泡排序,以保持數組的順序。
我不完全確定最壞情況的時間復雜度,但我認為它是 O(n^2)。 這個的時間復雜度是多少,以及它最像什么排序算法?
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));
}
}
我會說這是變相的插入排序。 因此,它具有 O(n^2) 的最壞情況和平均復雜度。
要看到這一點,首先要意識到在rise
方法中對rise
的遞歸調用是多余的:無論如何,在main
方法中從外部循環調用rise
將到達那里被引發的元素。 剩下的就是從列表中的每個元素的swap
方法中遞歸調用sink
。 這樣做是將每個元素放入列表中已經排序的初始位的右側 position 中:這本質上是插入排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.