[英]How to increment the size of an array within a loop
我有這個bubblesort代碼,我正在執行運行時分析,記錄排序數組所需的時間。 我想知道是否有任何方法可以使用循環增加數組的大小? 因為目前我手動一次遞增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));
}
}
不,您不能在創建后更改數組的大小。 您要么必須分配比您認為需要的更大的分配,要么接受必須重新分配的開銷需要增長。 當它發生時,您必須分配一個新的並將數據從舊數據復制到新數據。
您需要使用ArrayList,它將為您執行此操作,但需要額外的開銷。
或者,您可以在開始之前將數組分配為大小5000,並記錄到目前為止在變量中使用了多少元素(而不是依賴於array.length)
或者,您可以通過創建一個更大的新數組並將所有元素復制到它(System.arrayCopy(..))以及放入新數組來調整數組大小。
rizon的答案是正確的,你無法改變數組的大小。 順便說一句,你沒有在哪里重新創建陣列,也沒有看到你在哪里處理5000個元素。 如果您擔心處理時間,則不希望重新創建/調整數組大小,因為這樣效率非常低。 你會想要一個不同的解決方案。
這可能對你有所幫助
int[] intA = new int[100];
int sizeToIncrement = 100;
for(int i=0;i<5000;i++) {
if(i== intA.length ) {
intA = Arrays.copyOf(intA, intA.length + sizeToIncrement);
}
intA[i] = i;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.