Hi i’m relatively new to java programming. The following program i’ve written seems to be taking a lot of memory(around 240 MB, is it normal? – I don’t think so!)
Please suggest some ways to optimise this program so to reduce memory storage.
Program –
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}
Code –
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");
}
}
You need to remember that a Java program cannot run on its own, but need the Java Virtual Machine platform to handle memory, byte code execution and other tasks. The Oracle JVM uses quite a bit of memory to speed up execution so even trivially small programs come with a large start-up penalty.
This is why small utilities are rarely written in Java.
You need to measure inside the JVM to determine if you use too much memory. Use a profiler for that. JVisualVM in the JDK is a good, free starting profiler.