目录
一、求数组最小值
首先创建有一个长度是5的数组
然后给数组的每一位赋予随机整数
通过for循环,遍历数组,找出最小的一个值出来
0~100的 随机整数 的获取办法有多种,下面是参考办法之一:
(int)(Math.random()*100)
Math.random() 会得到一个0~1之间的随机浮点数,然后乘以100,并强转为整数即可。
public class Array01 {
public static void main(String[] args) {
int[] num = new int[5];//创建一个int类型的数组,长度为5
//为每一个数组元素赋予0~100的随机整数
//方法一!
// num[0]=(int)(Math.random()*100);
// num[1]=(int)(Math.random()*100);
// num[2]=(int)(Math.random()*100);
// num[3]=(int)(Math.random()*100);
// num[4]=(int)(Math.random()*100);
//得出每个元素的值,并找出最小的值
int n =1000;//求最小值时,先定义一个较大的值
for (int i = 0; i < num.length; i++) {
//下标为0~(5-1)
num[i]=(int)(Math.random()*100);//方法二!
System.out.print(num[i]+"\t");//每个元素的值
if (num[i]<n){
n=num[i];//替换得出最小值
}
}
System.out.println();
System.out.println(n);
}
}
二、数组反转
首先创建一个长度是5的数组,并填充随机数
使用for循环或者while循环,对这个数组实现反转效果
0~100的 随机整数 的获取办法有多种,下面是参考办法之一:
(int)(Math.random()*100)
Math.random() 会得到一个0~1之间的随机浮点数,然后乘以100,并强转为整数即可。
public class Array03 {
public static void main(String[] args) {
//创建一个长度为5的数组
int[] arrays = new int[5];
//每个元素赋值随机数
for (int i = 0; i < arrays.length; i++) {
arrays[i] = (int)(Math.random()*100);
System.out.print(arrays[i]+"\t");//打印
}
System.out.println();//换行
//先定义一个长度相等的空的数组
int[] arrays1 = new int[arrays.length];
//再反向赋值
for (int i = 0; i < arrays.length; i++) {
arrays1[i] = arrays[arrays.length-1-i];// -1 是因为下标是从0开始的
}
//再重新赋值给原来的数组
arrays = arrays1;
//增强for循环打印
for (int array : arrays) {
System.out.print(array+"\t");
}
}
}
三、排序
首先创建一个长度是5的数组,并填充随机数。
首先用选择法正排序,然后再对其使用冒泡法倒排序
注:所谓的正排序就是从小到大排序,倒排序就是从大到小排序
0~100的 随机整数 的获取办法有多种,下面是参考办法之一:
(int)(Math.random()*100)
Math.random() 会得到一个0~1之间的随机浮点数,然后乘以100,并强转为整数即可。
···选择法排序··· |
---|
public class Array06 {
public static void main(String[] args) {
//定义一个长度为5的数组
int[] array1 = new int[5];
//元素赋值:随机值
for (int i = 0; i < array1.length; i++) {
array1[i]=(int)(Math.random()*100);
}
//打印出原数组所有元素
System.out.print("原数组排序:"