写一个java的冒泡排序[1,9,2]
时间: 2024-05-06 22:21:14 浏览: 13
好的,这是一个Java的冒泡排序代码,可以对数组[1,9,2]进行排序:
```
public class BubbleSort {
public static void main(String[] args) {
int[] nums = {1, 9, 2};
bubbleSort(nums);
//输出排序后的结果
for (int num : nums) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
//交换相邻两个数的位置
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
}
```
这个代码使用了冒泡排序的思想,对数组中的元素进行排序。首先从头到尾遍历数组,比较每一对相邻的元素,将较大的元素向后移动。经过一次遍历,最大的元素就会被排到最后。然后再从头到倒数第二个元素遍历,重复上面的操作,直到整个数组都被排序。