Sorting of the array (bubble sort)

Bubble Sort:

1) Compare adjacent elements, and exchange if the last ascending criterion is violated.

2) It can be simplified and understood as:

第一次,找到所有元素中最大的放在最后一个位置,不再变动
第二次,找到剩余所有元素中最大的放在倒数第二位上,不再变动
以此类推,直到只剩一个元素时不再比较

3) The method of "sinking" or "floating" can be used for comparison.

Sorting process analysis:

int[] arr = {1,5,9,4};//ascending

Put 9 on arr[3] in the first round

1和5比,不换,{1,5,9,4}
5和9比,不换,{1,5,9,4}
9和4比,换,{1,5,4,9}-------9到达指定位置

In the second round, put 5 on arr[2]

1和5比,不换,{1,5,4,9}
5和4比,换,{1,4,5,9}-------5到达指定位置

In the third round, put 4 on arr[1]

1和4比,不换,{1,4,5,9}-----4到达指定位置

For example:

就像十个人抽10个球,到最后一个人抽的时候还用再抽么?
不用了,因为就剩下一个球了
Features:

5.1) When comparing arr.length elements, you only need to compare arr.length-1 round
5.2) Each round of comparison starts from the first element,
and every time it compares with its next element
5.3) The number that has been arranged is just No longer in comparison

Code:

	int[] bubble = new int[10];
//	给每个元素赋值1-100之间的随机数
	for(int i=0;i<bubble.length;i++){
    
    
		bubble[i] = (int)(Math.random()*100);
	}
	for(int i=0;i<bubble.length-1;i++){
    
    //控制轮数
		for(int j=0;j<bubble.length-1-i;j++){
    
    //控制对比次数
			if(bubble[j]>bubble[j+1]){
    
    //对比两个相邻的数
				int t = bubble[j];//将较大值放入空杯子
				bubble[j] = bubble[j+1];//将较小值前移
				bubble[j+1] = t;//将空杯子中的较大值后移
			}
		}
	}
//内层循环是用来控制比较次数的,那么对比次数的范围从何而来?
	i=0(1)3
	i=1(2)2
	i=2(3)1//从中可以发现每轮i的值和比较次数相加就是比较的轮数。
//同理比较的轮数减去i就是比较的次数了,用代码的实现:bubble.length-1-i	

Guess you like

Origin blog.csdn.net/qq_54177999/article/details/114435292