冒泡排序—排序系列

冒泡算法思想

冒泡算法的精髓在于两个嵌套循环,外循环控制的是循环次数,内循环控制的是数组元素的的角标,在循环体中交换数组元素位置。

冒泡算法代码实现

import java.util.Arrays;

public class Demo1 {
	public static void main(String[] args) {
		int[] arr = new int[] {1,43,8,4,2,287,5,88,5};
		Math math = new Math();
		math.run(arr);
		System.out.println(Arrays.toString(arr));
	}
}

class Math{
	public void run(int[] arr) {
		for(int i=0;i<arr.length;i++) {
			for(int j=0;j<arr.length-i-1;j++) {
				if(arr[j]>arr[j+1]) {
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44078014/article/details/106725017
今日推荐