Bubble sorting method: Records with smaller keywords are like bubbles floating up one after another, and records with larger keywords are like stones sinking, and one of the largest stones sinks to the bottom in each trip.
The essence of the algorithm: (the maximum value is the key point, it must be put to the end, so the loop) Every time, the comparison is scrolled backward from the first position, the maximum value is lowered to the bottom, the minimum value rises once, and the last bit advances forward (that is, the maximum value just determined by the last bit will no longer participate in the comparison, and the number of comparisons will be reduced by 1)
Complexity: Time complexity O(n2), space complexity O(1)
JAVA source code (successfully run, Date class is required)
public static void bubbleSort(Date[] days) {
int len = ;
Date temp;
for (int i = len - 1; i >= 1; i--) {
for (int j = 0; j < i; j++) {
if (days[j].compare(days[j + 1]) > 0) {
temp = days[j + 1];
days[j + 1] = days[j];
days[j] = temp;
}
}
}
}
class Date {
int year, month, day;
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
public int compare(Date date) {
return year > ? 1 : year < ? -1
: month > ? 1 : month < ? -1
: day > ? 1 : day < ? -1 : 0;
}
public void print() {
(year + " " + month + " " + day);
}
}
package testSortAlgorithm;
public class BubbleSort {
public static void main(String[] args) {
int array[] = { 5, 6, 8, 4, 2, 4, 9, 0 };
bubbleSort(array);
for (int i = 0; i < ; i++) {
(array[i]);
}
}
public static void bubbleSort(int array[]) {
int temp;
for (int i = - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}