动图如下:
代码:
public class BubbleSort {
public static void main(String[] args){
int[] nums = new int[]{ 8, 9, 1, 7, 2, 3, 5, 4, 6, 0 };
int[] res = sort(nums);
for(int i=0; i<res.length; i++){
System.out.print(res[i] + " ");
}
}
public static int[] sort(int[] nums){
if(nums == null){
throw new RuntimeException("数组为空");
}
int temp;
for(int i = 0; i<nums.length-1; i++){
for(int j = 0; j < nums.length-1-i; j++){ // 第i位以后都已经有序,没有必要再进行判断
if(nums[j] > nums[j+1]){
temp = nums[j+1];
nums[j+1] = nums[j];
nums[j] = temp;
}
}
}
return nums;
}
}