lal
BAN USER// Assuming arr[ ]and brr[ ] are two sorted arrays. merge these two arrays and stored in a third array crr[ ]. use Insertion sort, as it will not shuffle the elements , which are already sorted.
code:
------
public int median(int[] arr, int[] brr)
{
int[] crr=new int[arr.length+brr.length];
int i,tmp;
for(i=0;i<arr.length;i++)
crr[i]=arr[i];
for(int j=0;j<brr.length;j++)
crr[i++]=brr[j];
for(int k=1,l;i<crr.length;k++)
{
tmp=crr[k];
for(l=k;tmp<crr[l] && l>0;l--)
crr[l]=crr[l-1];
crr[l]=tmp;
}
int mid= crr.length/2;
int median;
if(crr.length%2==1)
median=crr[mid];
else
median= (crr[mid-1]+crr[mid])/2;
return median;
}
//Approach 1
1. check whether the data is huge, ie if the size of the input file more than the JVM heap size,
split the input into chunks , which can fit into memory
2. Sort the data in the chunk using merge sort (optional)
3. use the code to remove the duplicates.
public void approach1()
{
try {
BufferedReader br=new BufferedReader(new FileReader(new File("filepath")));
try {
Set<String> set=new HashSet<String>();
String line=null;
while((line=br.readLine())!=null)
{
set.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String temp = "A" + "B" + "C" ;
In this, Instead of creating multiple temporary objects in the Heap, here strings appended to string buffer .
String temp=new Stringbuffer().append("A").append("B").append("C").toString();
Stringbuffer , instead of creating a new String objects, it will expand the capacity and stores the string objects in that. This happens as part of JIT compiler optimization , so one object will be created.
- lal September 25, 2014