理解:
两两比较,交换后,得出的数组中的最大的数一次次的移动到数组的末尾,数组比较的次数也会一步步的少比较一个。数组a,两层循环。外层循环,保证比较次数为数组长度减1;内层循环,每次将数组比较a.length-i-1。
代码:
public class BubbleSort{ public static void main(String[] args) { int a[] = {5, 9, 6, 2, 3}; for(int i = 0; i < 5; i++) { for(int j = 0; j < 5-i-1; j++) { if(a[j] > a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } for(int i = 0; i < 5; i++) { System.out.print(a[i] + " "); } } }
文章来源: https://blog.csdn.net/weixin_44919928/article/details/91805281