-
算法描述:
1比较相邻的两个元素。如果第一个比第二个大,就交换它们两个。
2对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数。
3针对所有的元素重复以上的步骤,除了最后一个。
4重复步骤1~3,直到排序完成。
-
代码:
import java.util.Arrays;
/**
* 冒泡排序
*/
public class BubbleSort {
public static void main(String[] args) {
int[] nums = {5, 3, 6, 2, 7, 1};
System.out.println("排序前:" + Arrays.toString(nums));
bubbleSort(nums);
System.out.println("排序后:" + Arrays.toString(nums));
}
public static void bubbleSort(int[] nums) {
int len = nums.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
//升序排,如果降序就改成<
if (nums[j] > nums[j + 1]) { // 相邻元素两两对比
int temp = nums[j + 1]; // 元素交换
nums[j + 1] = nums[j];
nums[j] = temp;
}
}
}
}
}
运行结果:
排序前:[5, 3, 6, 2, 7, 1]
排序后:[1, 2, 3, 5, 6, 7]