public class ArrayDemo07 {
public static void main(String args[]) {
int score[] = { 77, 89, 87, 69, 90, 100, 75, 90 }; // 使用静态初始化声明数组
int score1[] = { 77, 89, 87, 69, 90, 100, 75, 90 }; // 使用静态初始化声明数组
long startTime1 = System.nanoTime();
for (int i = 1; i < score.length; i++) {
for (int j = 0; j < score.length; j++) {
if (score[i] < score[j]) { // 交换位置
int temp = score[i]; // 中间变量
score[i] = score[j];
score[j] = temp;
}
}
}
long endTime1 = System.nanoTime();
long time1 = endTime1 - startTime1;
System.out.println("冒泡算法所需时间:" + time1 + "纳秒.");
for (int x : score) {
System.out.print(x + "\t");
}
System.out.println();
long startTime2 = System.nanoTime();
for (int i = 0; i < score1.length; i++) {
for (int j = i + 1; j < score1.length; j++) {
if (score1[i] > score1[j]) { // 交换位置
int temp = score1[j]; // 中间变量
score1[j] = score1[i];
score1[i] = temp;
}
}
}
long endTime2 = System.nanoTime();
long time2 = endTime2 - startTime2;
System.out.println("直接算法所需时间:" + time2 + "纳秒.");
for (int x : score1) {
System.out.print(x + "\t");
}
System.out.println();
}
};
程序运行结果:
冒泡算法所需时间:3158纳秒.
69 75 77 87 89 90 90 100
直接算法所需时间:1974纳秒.
69 75 77 87 89 90 90 100