1、求数组元素的最大值、最小值、平均数、总和等
package com.laura.algorithm;
public class ArrayAlgo {
public static void main(String[] args) {
int[] arr1 = new int[] {23, 5, 23, 64, 66, -9, 75, -77, 3};
// 求最大值
int max = arr1[0];
for (int i = 1; i < arr1.length; i++) {
if (max < arr1[i]) {
max = arr1[i];
}
}
System.out.println("数组的最大值为:" + max);
// 求最小值
int min = arr1[0];
for (int i = 1; i < arr1.length; i++) {
if (min > arr1[i]) {
min = arr1[i];
}
}
System.out.println("数组的最小值为:" + min);
// 求总和
int sum = 0;
for (int i = 0; i < arr1.length; i++) {
sum += arr1[i];
}
System.out.println("数组的总和为:" + sum);
// 求平均值
double avg = sum / (double)arr1.length;
System.out.println("数组的平均数为:" + avg);
}
}
2、数组的复制、反转、查找(线性查找、二分法查找)
package com.laura.algorithm1;
public class Algorithm1 {
public static void main(String[] args) {
int[] array1, array2;
array1 = new int[] {2, 3, 5, 7, 11, 13, 15, 17, 19};
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
// array2 = array1; // 引用类型变量:地址赋值(指向同一内存值,非数组值复制)
array2 = new int[array1.length];
for (int i = 0; i < array2.length; i++) {
array2[i] = array1[i];
}
// 修改array2不影响array1
for (int i = 0; i < array2.length; i++) {
if (i % 2 == 0) {
array2[i] = 0;
}
}
System.out.println();
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
// 数组的反转-方式1
for (int i = 0, j = array1.length -1; i < j; i++, j--) {
int tmp = array1[i];
array1[i] = array1[j];
array1[j] = tmp;
}
System.out.println();
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
// 数组的反转-方式2
for (int i = 0; i < array1.length / 2; i++) {
int tmp = array1[i];
array1[i] = array1[array1.length - i - 1];
array1[array1.length -i -1] = tmp;
}
System.out.println();
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
}
}
package com.laura.algorithm1;
public class Algorithm2 {
public static void main(String[] args) {
// 线性查找
String[] arr1 = new String[] {"MM", "JJ", "GG", "DD", "AA", "BB", "CC"};
String search = "CC";
for (int i =0; i < arr1.length; i++) {
if (arr1[i].equals(search)) {
System.out.println("Found " + search + ", Index is " + i);
break;
}
}
// 二分法(前提数组是有序的,否则无法使用)
int[] arr2 = new int[] {-99, -54, -2, 0, 2, 33, 43, 256, 999};
int searchNumber = 256;
int head = 0;
int end = arr2.length - 1;
while (head <= end) {
int middle = (head + end) / 2;
if (arr2[middle] == searchNumber) {
System.out.println("Found " + searchNumber + ", Index is " + middle);
break;
} else if (arr2[middle] > searchNumber) {
end = middle - 1;
} else if (arr2[middle] < searchNumber) {
head = middle + 1;
}
}
}
}
3、数据元素的排序
选择排序(直接选择排序、堆排序)
交换排序(冒泡排序、快速排序)
插入排序(直接插入排序、折半插入排序、Shell排序)
归并排序
桶式排序
基数排序
排序方式的选择,通常可以用三个指标衡量:
(1)时间复杂度:分析关键字的比较次数和记录的移动次数
(2)空间复杂度:分析排序算法种需要多少辅助内存
(3)稳定性:若两个记录A和B的关键字值相等,但排序后A、B的先后次序保持不变,则称这种排序算法是稳定的