Bubble sort
It repeatedly visits the array to be sorted, compares two elements at a time, and swaps them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array 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,
You can clearly understand the algorithm flow of bubble sort from the output.
Selection sort
In each pass, the smallest (or largest) element is selected from the data elements to be sorted, and the order is placed at the end of the sorted array until all the data elements to be sorted are arranged.
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"); } } }
It can be seen from the code that in each round of comparison, nums[i] is compared with each element in the array.
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,
From the output results, it is easy to see the algorithmic difference between it and bubble sort.
For more in-depth explanations of the differences between Java bubble sort and selection sort, please pay attention to the PHP Chinese website!