冒泡排序(Java)
package day01; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class BubbleSort { public static void main(String[] args) { System.out.println("请输入要随机生成的数组长度"); Scanner s =new Scanner(System.in); int num = s.nextInt(); s.close(); //随机生成一个包含十个元素的数组 int[] arr = new int[num]; Random ran = new Random(); //随机生成数 for(int i = 0;i<=(num - 1);i++) { arr[i] = ran.nextInt(100); } System.out.println("随机生成的数组:" + Arrays.toString(arr)); //用冒泡排序给数组排序 int a = 0; //中间变量 for(int j = (arr.length-1);j>0;j--) { for(int h = 0; h <j;h++) { if(arr[h]>arr[h+1]) { a = arr[h]; arr[h] = arr[h+1]; arr[h+1] = a; } } } System.out.println("数组从小到大排序为:" + Arrays.toString(arr)); } }