- package com.heima.bubble;
- public class Demo1_Bubble {
- /**
- * 冒泡排序
- */
- public static void main(String[] args) {
- int[] arr = {5,7,9,2,1,3,5,76,8}; //输入一个数组
- for (int i = 0; i < arr.length-1; i++) { //外层循环控制
- for (int j = 0; j < arr.length-1-i; j++) { //内层循环控制比较次数-1防止数组角标越界-提高效率
- if (arr[j] > arr[j+1]) {
- int temp = arr[j]; //两数通过第三方变量交换
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
-
- for (int i = 0; i < arr.length; i++) { //打印数组
- System.out.print(arr[i]+" ");
- }
- }
- }
复制代码 |
|