Sorting first: bubble sort

Sorting is very common in daily life. For example, after we finish the exam, the teacher will sort according to our scores from high to low, so as to understand our learning situation; in physical education class, the teacher will according to the height of the students Sorting from low to high or from high to low is more convenient for teaching. It can be seen that sorting is very common and practical in life. For us, sorting is not difficult, but for computer programs, sorting is not like us.

Bubble sort process

You can think of a computer program as a person with a high degree of myopia (as for the degree of myopia, probably a group of people standing in front of you, but you can only see the two people in front of you), because you can only see To the relationship between two people, it is determined that you can only compare the heights of two adjacent people in turn, and exchange the positions of the two people as needed. If you want to line up basketball players from low to high, start from the leftmost side of the team and compare the heights of the two players in front of you in turn. If the height of the player on the right is lower than that of the player on the left, then swap the two players. Otherwise, you will not swap. When you first line up to the left and right of the team, you will find that the tallest person in the team has already stood at the rightmost position of the team, and then you are back to the top of the team. On the left, repeat the process just now, and finally the team members will stand in order from low to high. Now we use 7 numbers instead of basketball players and sort them from small to large. The process is shown in the figure below. Red represents the maximum value obtained by this sorting.
Insert picture description here
Code:

package demo;

public class BobbleSortApp{
    
    
	public static void main(String[] args) {
    
    

        int[] numbers=new int[]{
    
    2,8,5,9,10,6,4};
        for(int i=numbers.length-1;i>1;i--)
        {
    
    
            for(int j=0;j<i;j++)
            {
    
    
                if(numbers[j]>numbers[j+1])
                {
    
    
                    int temp=numbers[j];
                    numbers[j]=numbers[j+1];
                    numbers[j+1]=temp;
                }
            }
        }
        System.out.println("从小到大排序后的结果是:");
        for(int i=0;i<numbers.length;i++)
            System.out.print(numbers[i]+" ");
    }

}

Guess you like

Origin blog.csdn.net/qq_43825377/article/details/108969969