Dig into the difference between Java bubble sort and selection sort

  • 2020-04-01 02:03:10
  • OfStack

Bubble sort
It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if they are in the wrong order. The task of visiting a sequence is repeated until there is no need to swap, that is, the sequence has been sorted.
The code is as follows:

public class nums {
     public static void main(String[] args){
         int []nums = {5,4,3,2,1};
         for(int i = 0; i < nums.length; i++){
             for(int j = 0; j < nums.length-i-1; j++){
                 if(nums[j] > nums[j+1]){
                     int temp = nums[j];
                     nums[j] = nums[j+1];
                     nums[j+1] = temp;
                 }
             }
             for(int x = 0;x < nums.length;x++){
                  System.out.print(nums[x]+",");
              }
             System.out.print("n");
         }
     }
 }

The output after each round of comparison is as follows:

1 4,3,2,1,5,
2 3,2,1,4,5,
3 2,1,3,4,5,
4 1,2,3,4,5,
5 1,2,3,4,5,

The algorithm flow of bubble sort can be clearly understood from the output.
Selection sort
Each pass selects the smallest (or largest) element from the data elements to be sorted and places it at the end of the sorted sequence until all the data elements to be sorted are sorted.
The code is as follows:

public class nums {
     public static void main(String[] args){
         int []nums = {5,4,3,2,1};
         for(int i = 0; i < nums.length; i++){
             for(int j = 0; j < nums.length; j++){
                 if(nums[i] < nums[j]){
                     int temp = nums[i];
                     nums[i] = nums[j];
                     nums[j] = temp;
                 }
             }
             for(int x = 0;x < nums.length;x++){
                  System.out.print(nums[x]+",");
              }
             System.out.print("n");
         }
     }
 }

You can see from the code that nums[I] is compared to each element in the array for each round of comparisons.
The output after each round of comparison is as follows:

1 5,4,3,2,1,
2 4,5,3,2,1,
3 3,4,5,2,1,
4 2,3,4,5,1,
5 1,2,3,4,5,

It's still easy to see from the output that it differs algorithmically from bubble sort.

Related articles: