一、代码展示
public class test9 {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// 每次遍历后,最大的i+1个元素已经排好序
for (int j = 0; j < n - i - 1; j++) {
// 如果当前元素大于下一个元素,则交换
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 打印数组
public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
// 测试
public static void main(String[] args) {
int[] arr = {1,5,6,4,8,9};
System.out.println("排序前的数组:");
printArray(arr);
bubbleSort(arr);
System.out.println("排序后的数组:");
printArray(arr);
}
}
二、介绍
在等待排序的一组数中,将相邻的两个数进行比较,若前面的数比后面的数大就交换两数,否则不交换;如此重复遍历下去,直到没有再需要交换的元素,这样就完成排序。
解释(有点难懂):
- 冒泡排序的基本思想是通过多次遍历数组,每次将当前未排序部分的最大元素移动到正确的位置。
- 在每一次外层循环中,我们都会将未排序部分的最大元素放到正确的位置。
- 因此,每完成一次外层循环,未排序部分的最大元素就会被放到正确的位置,这样未排序部分的大小就会减少1。
j < arr.length - i - 1
这个条件确保我们在内层循环中只对未排序部分进行遍历,避免对已经排序好的元素进行不必要的比较。
三、实战!!!
那用冒泡排序怎么写呢???
想必各位有更好的方法,会的教我,务必!!!
我的(老实)代码如下:
public class code{
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12};
nums = moveZeroes(nums);
for (int num : nums)
System.out.print(num + " ");
}
public static int [] moveZeroes(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (nums[j] == 0) {
// 交换相邻元素,把零往后移
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
return nums;
}
}