How to understand bubble sort

What is bubbling?

      Just like the bubbles floating up, the smaller value is in the front, and the larger value is in the back. That is to say, in a set of numbers, one of the numbers is compared with other numbers. If this number is smaller than the other numbers, then it is in front of the larger number until it encounters a smaller number.

    If I have already compared the magnitudes of two numbers, how can I make them change their positions relative to each other? Before solving this problem, let's ask a question:

      There is a cup A filled with water, and a cup B filled with water, I want to exchange the water in cup A and cup B, what should I do? The solution is to find an empty cup. That is to say, I pour the water in the A cup into the empty cup, then pour the water in the B cup into the A cup, and finally pour the water in the empty cup into the B cup, so that the A and B are realized. exchange.

      Using this idea, we can solve the problem of how to exchange positions of two numbers.

Please see the code below:

int []array=new int[*]

int temp=0;

for(int i=0;i<array.Length-1;i++)

{

for(int j=i+1;j<array.Length;j++)

{

if(array[j]<array[i])

{

temp=array[i];

array[i]=array[j];

array[j]=temp

}

}

}

This is a method that uses two loops, compares the two values, and then uses the above idea to solve the method of swapping the positions of the two numbers.

Some of my own understanding, I hope you can like it! ! !

If there are any mistakes, please bear with me!




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325735228&siteId=291194637