Matrix算法(2)---两种算法的执行时间比较

实现以下Matrix算法:
[img]http://dl.iteye.com/upload/attachment/464904/8b74cd03-5d8b-3f4e-bc35-b1e14efee297.jpg[/img]

第一种算法:

import java.io.IOException;

public class MatrixTest_2A {
public static void main(String[] args) throws IOException {
long time_begin = System.currentTimeMillis();
int[][] data = generateMatrix(6);
long time_end = System.currentTimeMillis();
System.out.println("程序执行时间:" + (time_end - time_begin));
for (int i = 0; i < data.length; i++) {
for (int m = 0; m < data[i].length; m++) {
if (data[i][m] == 0)
System.out.print("\t");
else
System.out.print(data[i][m] + "\t");
}
System.out.println();
}
}

private static int[][] generateMatrix(int n) {

int[][] ret = new int[n][n];

int maxValue = n * n;

int directionStatus = 1;

int rowIndex = 0;
int colIndex = 0;

int count = 0, temp = 0;

for (int i = 1; i <= maxValue; i++) {

ret[rowIndex][colIndex] = i;

if (directionStatus == 1) {
colIndex++;
temp = 0;
directionStatus = 2;
} else if (directionStatus == 2) {
rowIndex++;
if (temp < count && count != 0) {
directionStatus = 2;
temp++;
} else {
temp = 0;
directionStatus = 3;
}
} else if (directionStatus == 3) {
if (colIndex > 0)
colIndex--;

if (temp < count && count != 0) {
directionStatus = 3;
temp++;
} else {
temp = 0;
directionStatus = 4;
}
if (colIndex == 0)
count++;
} else if (directionStatus == 4) {
rowIndex = 0;
for (int j = 1; j <= count + 1; j++) {
colIndex++;
}
directionStatus = 2;
}
}
return ret;
}
}


第二种算法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MatrixTest_2B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入您需要的矩阵的边长: ");

String inputString = br.readLine();
long time_begin = System.currentTimeMillis();
int len = Integer.parseInt(inputString);
int[][] a = new int[len + 1][len + 1];
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= i; j++) {
a[i][j] = i * i - (j - 1);
}
for (int k = 1; k < i; k++) {
a[k][i] = (i - 1) * (i - 1) + k;
}
}
long time_end = System.currentTimeMillis();
System.out.println("程序执行时间:" + (time_end - time_begin));
// 输出矩阵
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= len; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}

一个 矩阵 的 算法 ,有 很多 种 算法,各个算法的执行效率都是不同的!算法 越先进,执行效率越高,但 这种 先进 算法的 诞生,需要认真观察和推敲才能得出!刚才,上面那个矩阵 的 算法,在都产生矩阵边长为:1000时,两种执行时间分别为:第一个是22毫秒,第二个是55毫秒,相差33毫秒。可见,相差的时间 还 是 蛮多的!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值