Bubble Sort
- Idea: Compare adjacent elements in pairs, put the larger ones in the back. After the first time, the maximum value appears at the maximum index. If you continue with the same principle, you can get a sorted array. .
- Example
1. Original array
2. After the first sorting
3. After the second sorting
4. After the third sorting
5. After the fourth sorting
- law
1. Two-by-two comparison, put the bigger one later
2. After each comparison is completed, the next comparison will always reduce one element comparison
3. The first comparison, there are zero elements that are not
compared, the second comparison, there is one element Not
compared to the third time, there are two elements not compared
...
4. A total of -1 times need to compare array length
Code
public class Test {
public static void main(String[] args) {
int[] array=new int[]{
24,69,80,57,13};
System.out.println("排序前");
printArray(array);
bubbleSort(array);
System.out.println("排序后");
printArray(array);
}
public static int[] bubbleSort(int[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-1-i;j++) {
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
public static void printArray(int[] arr){
System.out.print("[");
for (int i=0;i<arr.length;i++){
if(i==arr.length-1){
System.out.print(arr[i]);
}
else{
System.out.print(arr[i]+",");
}
}
System.out.println("]");
}
}
Java introductory basic learning (1)
Java introductory basic learning (2)
Java introductory basic learning (3)
Common objects of advanced java (1)