Detailed explanation of the difference between Java bubble sort and selection sort
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool