This is the 4th day of my participation in the August Gwen Challenge **
I’m going to complete the bubble sort today
The core idea of bubble sort is to swap the largest number of remaining elements, which is a bit like bubble sort, so it’s called bubble sort, no tricks
Compare two adjacent elements, swapping the one with the highest value to the right
Here’s an example:
Array:,44,38,5,47,15,36,26,27,2,46,4,19,50,48 [3]
The first round:
We go through the set of numbers, comparing them in pairs, moving the larger number back, and after a loop, the largest number, 50, is successfully placed in the last position
The second round:
Just iterate through the preceding elements, comparing them in pairs, moving the larger numbers back, and after a loop, the largest number, 48, is successfully placed in the second-to-last position
And so on:
Two-layer loop: the outer loop loops the position, and the memory loop selects the maximum value
Take a look at the GIF:
,package com.example.demo;
import java.util.Arrays;
/** * bubble sort **@authorParsley * /
public class Bubble {
public static void bubble(int[] a) {
for (int i = a.length - 1; i >= 0; i--) {
for (int j = a.length - 1; j >= 0; j--) {
if (a[i] > a[j]) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println(Arrays.toString(a));
}
public static void main(String[] args) {
int[] a = {3.44.38.5.47.15.36.26.27.2.46.4.19.50.48}; bubble(a); }}Copy the code
Summary: Bubble algorithm should be the entry, but for the beginning of the entry algorithm of the students is still very important, everything is difficult at the beginning, a good entry is very important, keep confidence, keep patience, indomitable