嗨,我相對較新的Java編程。我寫的下列程序似乎需要大量的內存(大約240 MB,這是正常的嗎? - 我不這麼認爲!) 請建議一些優化此程序的方法,以減少內存存儲空間。Java程序消耗太多內存
計劃 -
You have 2 sorted array suppose arr1[4] and arr2[3]
now we have to combinely sort them using very little extra space(i.e. in-place sort)
ex..arr1[4]={5,8,11,14,16}
arr[2]={1,7,10}
then result should be--in arr1[4]={1,5,7,8,10}
in arr2[3]={11,14,16}
代碼 -
import java.util.*;
class sort_in_place
{
public static void main(String args[])
{
// input 2 sorted arrays
int []a = {5,8,11,14,16};
int []b = {1,7,10};
System.out.println("initial array: a = "+Arrays.toString(a)+" b = "+Arrays.toString(b)+"\n");
// use extra space to store the array 'a' elements.
int key = 0, i=0;
for(i=0; i<a.length ; i++)
{
key = a[i]; // store value in temporary variable key.
// if key is greater than 1st element of array 'b' then exchange their values and sort array 'b'
if(key > b[0])
{
int j = 1;
a[i] = b[0];
while(j<b.length && key > b[j])
{
b[j-1] = b[j];
j++;
}
b[j-1] = key;
}
}
System.out.println("final array: a = "+Arrays.toString(a)+" b = "+Arrays.toString(b)+"\n");
}
}
定義「使用24M」;你是如何得到這個數字的?另外這很難讀。 –
..此外,請編輯您的問題,以便您的代碼放置在代碼片段中。 –
你的性能目標數量是多少?(正如戴夫所評論的)你使用的是什麼確切的值(在Windows上的性能指標......)?當你沒有好的可測量目標時,「優化」某些東西並不是一個好主意。 –