gpt4 book ai didi

java - 为冒泡排序执行计时

转载 作者:行者123 更新时间:2023-12-01 04:44:07 25 4
gpt4 key购买 nike

我希望能够看到冒泡排序对数组中的所有元素进行排序需要多长时间。如何测量时间?

public class Bubble {
static int[] nums = {5, 4, 3, 2, 1};

public static void main(String[] args) {
bubble(nums);
for(int i=0; i<nums.length; i++){
System.out.print(nums[i] + " ");
}
}

// bubble sort
public static void bubble(int[] unsorted){
int temp;
boolean sorted = false;
int length = unsorted.length;

while(!sorted){
sorted = true;

for(int i=0; i<length-1; i++){
if(unsorted[i] > unsorted[i+1]){
temp = unsorted[i];
unsorted[i] = unsorted[i+1];
unsorted[i+1] = temp;
sorted = false;
}
}
}
}
}

最佳答案

摘自Diastropism对how do I time a methods excecution in java的回答:

There is always the old-fashioned way:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = endTime - startTime;

关于java - 为冒泡排序执行计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com