目录
1、打擂台找出数组的最大值和最小值
//打擂台找出数组的最大值
public static void a() {
int len = (int) (Math.random() * 6 + 8);
int[] array = new int[len];//len==数组长度
//随机向数组中的每一个元素赋值
for (int i = 0; i < len; i++) {
array[i] = (int) (Math.random() * 100 + 1);
}
System.out.println("数组内容是:" + Arrays.toString(array));
// 找出数组中的最大值
// 通过打擂台方式
int max = array[0];
for (int i = 1; i < len; i++) {
if (array[i] > max) {
// 擂主就是下标为i的元素
max = array[i];
}
}
System.out.println("最大值为:" + max);
}
public static void b() {
int len = (int) (Math.random() * 10 + 3);
int[] array = new int[len];
//随机向数组中的每一个元素赋值
for (int i = 0; i < len; i++) {
array[i] = (int) (Math.random() * 100 + 1);
}
System.out.println("数组输出为:" + Arrays.toString(array));
int min = array[0];
for (int i = 0; i < len; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("最小值为:" + min);
}
结果:
2、通过冒泡排序对随机数组进行排序
//通过冒泡的方式进行排序
public static void d() {
int len = (int) (Math.random() * 5 + 6);
int[] array = new int[len];//定义一个长度为len的数组
//通过循环的方式给数组赋值
for (int i = 0; i < len; i++) {
//随机输出数组的值1-100间
array[i] = (int) (Math.random() * 100 + 1);
}
//输出数组值
System.out.println("原始数组的值为:" + Arrays.toString(array));
// 重复执行多次位移操作
for (int j = 0; j < len - 1; j++) {
//通过冒泡方式将最大值移动到最后一位
for (int i = 0; i < len - 1; i++) {
// 如果我大于我的下一位
if (array[i] > array[i + 1]) {
// 交换
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
System.out.println("新数组的内容为:" + Arrays.toString(array));
}
结果: