数组中涉及的常见算法:
1.求数组元素的最大值、最小值、总和、平均数;
2.数组的复制、反转;
3.数组元素的排序。
1.求数组元素的最大值、最小值、总和、平均数:
public class Test1{
public static void main(String[] args){
int[] arr = new int []{4,9,5,8,1,2,7,6};
int max = arr[0];
for(int i = 0;i < arr.length;i++) {
if(max < arr[i]) {
max = arr[i];
}
}
System.out.println(max);
int min = arr[0];
for(int j = 0;j < arr.length;j++) {
if(min > arr[j]) {
min = arr[j];
}
}
System.out.println(min);
int sum = 0;
for(int i = 0;i < arr.length;i++) {
sum += arr[i];
}
System.out.println(sum);
double ave = 0.0;
double sum1 = (double) sum;
ave = sum1 / arr.length;
System.out.println(ave);
}
}
2.数组的复制、反转:
public class Test1{
public static void main(String[] args){
int[] arr = new int []{4,9,5,8,1,2,7,6};
int[] copy = new int[arr.length];
for(int i = 0;i < arr.length;i++) {
copy[i] = arr[i];
System.out.println(copy[i]);
}
int[] rev = new int[arr.length];
for(int i = 0;i < arr.length;i++) {
rev[i] = arr[arr.length-i-1];
}
arr = rev;
for(int i = 0;i< arr.length;i++) {
System.out.println(arr[i]);
}
}
}
3.数组元素的排序(冒泡排序):
public class Test1{
public static void main(String[] args){
int[] arr = new int []{4,9,5,8,1,2,7,6};
int s = 0;
for(int i = 0;i < arr.length-1 ;i++) {
for(int j = 0;j < arr.length-1-i;j++) {
if(arr[j] > arr[j+1]) {
s = arr[j];
arr[j] = arr[j+1];
arr[j+1] = s;
}
}
}
for(int i = 0;i < arr.length;i++) {
System.out.println(arr[i]);
}
}
}
如果冒泡排序要从大到小排序,只需改一个条件即可,即:
if(arr[j] < arr[j+1])