Bubble sort algorithm principle and JAVA implementation code

  • 2020-04-01 02:47:24
  • OfStack

Bubble sort A record with a smaller keyword is like a bubble floating up one pass at a time. A record with a larger keyword is like a rock sinking down, with one of the largest rocks sinking down each pass.

Algorithm essence :(the maximum value is the key point, must be put to the last, so the cycle) every time from the first scroll back to the comparison, make the maximum bottom, the minimum up once, the last bit forward (that is, the last bit of the maximum just determined no longer participate in the comparison, the number of comparison minus 1)

Complexity: time complexity O(n2), space complexity O(1)

JAVA source code (to run successfully, need Date class)


 public static void bubbleSort(Date[] days) {
  int len = days.length;
  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 > date.year ? 1 : year < date.year ? -1
    : month > date.month ? 1 : month < date.month ? -1
      : day > date.day ? 1 : day < date.day ? -1 : 0;
 }
 public void print() {
  System.out.println(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 < array.length; i++) {
   System.out.println(array[i]);
  }
 }
 public static void bubbleSort(int array[]) {
  int temp;
  for (int i = array.length - 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;
    }
   }
  }
 }
}


Related articles: