【发布时间】:2021-04-11 22:30:06
【问题描述】:
我使用与 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));
}
}
【问题讨论】:
-
您的问题到底是什么?计算它的时间复杂度?
-
@user202729 那个,以及排序算法的名称是什么,如果有人知道的话。