Question
Add a merge() method to the OrdArray class discussed in Section 2.3 of the lecture notes. The merge() method should accept two ordered source arrays
Add a merge() method to the OrdArray class discussed in Section 2.3 of the lecture notes. The merge() method should accept two ordered source arrays as parameters and merge them into an ordered destination array. Add appropriate code in main() of the OrderedApp class that inserts some numbers into the two source arrays, invokes merge(), and displays the contents of the two source arrays and the resulting destination array. Note: The source arrays may be of different sizes. In your algorithm you will need to compare the keys of the source arrays, picking the smallest one to copy into the destination array. Thus, you will need to handle the situation when one source array exhausts its contents before the other.
public class OrdArray
{
private long[] a;
private int nElems;
public OrdArray(int max)
{
a = new long[max];
nElems = 0;
}
public int size()
{
return nElems;
}
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;
while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn;
else if(lowerBound > upperBound)
return nElems;
else
{
if(a[curIn] < searchKey)
lowerBound = curIn + 1;
else
upperBound = curIn - 1;
}
}
}
public void insert(long value)
{
int j;
for(j=0; j if(a[j] > value) break; for(int k=nElems; k>j; k--) a[k] = a[k-1]; a[j] = value; nElems++; } public boolean delete(long value) { int j = find(value); if(j==nElems) return false; else { for(int k=j; k a[k] = a[k+1]; nElems--; return true; } } public void display() { for(int j=0; j System.out.print(a[j] + " "); System.out.println(" "); } } class OrderedApp { public static void main(String[] args) { int maxSize = 100; OrdArray a,b,c; a= new OrdArray(maxSize); b= new OrdArray(maxSize); c= new OrdArray(maxSize); a.insert(00); a.insert(33); a.insert(66); a.insert(88); a.insert(44); a.insert(99); a.insert(11); a.insert(77); a.insert(55); a.insert(22); b.insert(23); b.insert(63); b.insert(13); b.insert(43); OrdArray.merge(a,b); System.out.print("Array A="+" "); a.display(); System.out.print("Array B="+ " "); b.display(); System.out.print("Array c: "); c.display(); System.out.println(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started