Java数组常用算法

找出数组中的最大值:

double[] a = new double[N];
double aMax = a[0];
for(int i = 1; i < a.length; i++)
    if(a[i] > aMax) aMax = a[i];

计算数组元素的平均值:实现思路,先求和,再计算平均值。

double[] a = new double[N];
int n = a.length;
double sum = 0.0;
for(i = 0; i < a.length; i++)
    sum += a[i];
double average = sum / n

复制数组:

double[] a = new double[N];
double[] b = new double[a.length];
for(int i = 0; i < a.length; i++)
    b[i] = a[i];

颠倒数组元素的顺序:

double[] a = new [N];
for(int i = 0; i < a.length/2; i++)
    double temp = a[i];
    a[i] = a[a.lenght-1-i];
    a[a.lenght-1-i] = temp;

矩阵相乘:

double[] a = new double[N];
double[] b = new double[N];
int n = a.length;
for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
    {
        //计算行i和列j的点乘
        for(int k = 0; k < n; k++)
            c[i][j] = a[i][k] * b[k][j]
    }

 

你可能感兴趣的:(Java)