I made a sorting algorithm using the same kind of logic of the heapify algorithm. 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. 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). 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));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…