我有这个冒泡排序代码,我正在执行运行时分析以记录对数组进行排序所需的时间。我想知道是否有任何方法可以使用循环增加数组的大小?因为目前我手动将其增加 100,并且我需要达到 5000 的数组大小。
public class BubbleSortworking{
public static void main (String[] args) {
Random rand = new Random();
int myArray[] = new int[100]; //How to increment this using a loop
int count, count2;
count2 = 2; //amount of times to run the loop
//repeats the bubble sort, while also producing new arrays each time
for (count = 0; count < count2; count++){
for (int i = 0; i < myArray.length; i++){
myArray[i] = rand.nextInt(100) + 1; //produce numbers between 1 - ?
//System.out.print(myArray[i] + ", "); //displays unsorted array
}
bubble(myArray);
// uncomment below 2 lines to prove each new sorted array cycle is unique
//for (int i = 0; i < myArray.length; i++)
// System.out.print(myArray[i] + ", ");
}
}
public static void bubble(int myArray[]){
int temp;
long start = System.nanoTime();
//System.out.println("start " + start);
//for (count = 0; count < count2; count++){
for (int i=0; i < myArray.length - 1; i++) {
for(int j=myArray.length - 1; j > i; j--) {
if (myArray[j] < myArray[j-1]){
temp = myArray[j];
myArray[j] = myArray[j-1];
myArray[j-1] = temp;
}
}
}
long end = System.nanoTime();
System.out.println(end - start);
//System.out.println("elapsed time " + (end - start));
}
}