Java implements bubble sort algorithm

  • 2020-05-17 05:24:05
  • OfStack

Bubble sort:

If it is greater than/less than (depending on whether it needs to be sorted in ascending or descending order), then the substitution is performed. Otherwise, no change is made
So if I go down 1 round, I compare n minus 1 times, n is equal to the number of elements; n - 2, n - 3... One goes all the way to the last round, and we compare it one time
所以比较次数为递减:从n-1 to 1
So the total number of comparisons is: 1+2+3+... + (n - 1), as n arithmetic formula (1 + 1) / 2 * (n - 1) = = > n/2*(n-1) == > (n^2-n) * 0.5
Large O is used to represent the time complexity of the algorithm: O(n^2), ignoring the coefficient 0.5 and the constant -n.

Algorithm thought

It repeatedly visits the sequence to be sorted, compares two elements once, and swaps them if they are in the wrong order. The task of visiting a sequence is repeated until no exchange is needed, that is, the sequence has been sorted.

The algorithm got its name because smaller elements slowly "float" to the top of the sequence by swapping.

The code is as follows:


int[] array = {56, 15, 10, 69, 1, 21, 6, 85, 30, 45, 73, 93}; 
     
    // Bubble sort  
    for (int i = 0; i < array.length; i++) { 
      for (int j = i+1; j < array.length; j++) { 
        if (array[i] >= array[j]) { 
          int temp = array[i]; 
          array[i] = array[j]; 
          array[j] = temp; 
        } 
      } 
    } 
     
    System.out.print(" The results of bubble sort are:  "); 
    for (int i : array) { 
      System.out.print(i + " "); 
    } 

Related articles: