First, the basic idea:
Bubble sort is a simple sort of exchange class. The basic idea is to scan the elements to be sorted from the beginning, compare the adjacent elements in sequence during the scanning process, and move the elements with large key values back. After each pass, the element with the highest key value is moved to the end, where the element's position is noted, and the next order only needs to be compared to this location until all the elements are sorted in an orderly manner.
Generally, the n elements are bubbled up, and a total of n-1 is required. The 1th trip needs to compare n-1 times, 2nd trip needs to compare n-2 times, ... The first trip needs to be compared n-i times.
Second, the implementation of the algorithm
public class bubblesort{
public static void Main (String args[]) {
Int[] values={3,1,6,2,9,0,7,4,5};
Sort (values);
for (int i=0;i<values.length;i++) {//The elements in the print group after sorting
System.out.println ("Index:" +i+ "value:" +values[i]);
}
}
public static void sort (int[] values) {
int temp;
for (int i=0;i<values.length;i++) {//Number of times
for (int j=0;j<values.length-i-1;j++) {//Number of comparisons
if (Values[j]>values[j+1]) {
TEMP=VALUES[J];
VALUES[J]=VALUES[J+1];
Values[j+1]=temp;
}
}
}
}
}
Using Java to implement bubble sort method