This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

1. Algorithm idea

For the data to be sorted, compare two adjacent numbers from top to bottom and adjust them, moving the largest number down and popping the smaller number up. That is, compare the two adjacent data elements in turn, place the smaller number to the left, and repeat the same operation until all the data elements to be sorted are sorted.

2. Case analysis

For example: we’re going to the height of ten people stood in a row and asked them to line up from low to high, according to the height is set to 10 Numbers 0-9, the adjacent two ordinal comparison, if the left is higher than the right of the people, by exchanging the positions of the two men, otherwise don’t exchange, until the last two, namely the finished sorting. After a sorting, the tallest person is already on the far right.

Result after one sort :(move the highest person to the last position after one sort)

So many times to sort, and finally complete the whole sort.

3. Algorithm analysis

(Sort from small to large)

  1. If a[I]>a[I +1], then the two numbers are exchanged, otherwise the two numbers are not changed.

  2. Each cycle is a cycle, and since there are multiple cycles to go through, that is, there is another cycle outside, so there is a double cycle.

4. Algorithm code :(Java version)

/** * Bubble sort algorithm *@author xcbeyond
 *
 */

public class BubbleSort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[] ={13.15.37.89.60.39.12.109.56.72};int i = 0;
		int j = 0;
		
		for(i=0; i<10; i++) System.out.print(a[i]+"");
		System.out.println();
		
		for(i=0; i<a.length; i++)for(j=0; j<a.length-i-1; j++) {if(a[j]>a[j+1])
				{
					int temp;
					temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp; }}for(i=0; i<10; i++) System.out.print(a[i]+""); }}Copy the code