Hello! I am having trouble with finding the nth largest element given two arrays
ID: 3623500 • Letter: H
Question
Hello! I am having trouble with finding the nth largest element given two arrays of size n by using the divide and conquer strategy. I'm not quite sure what I am doing wrong but here's what I've done so far:private static int nthLargest(int []a, int[] b, int number, int start, int end)
{
int center = ((start + end)/2) + 1;
if(number == a[center])
return a[center];
if(number == b[center])
return b[center];
if(a[center] < b[center])
{
if(number < a[center])
nthLargest(a, b, number, start, center);
else
nthLargest(a, b, number, center, end);
}
return 0;
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int[] a = {2,4,6,19,22,25};
int[] b = {7,13,14,21,23,33};
int end = a.length;
System.out.print("Enter the nth Biggest number to find: ");
int number = kbd.nextInt();
int answer = nthLargest(a, b, number, 0, end);
}
I would appreciate any assistance. Thanks!
Explanation / Answer
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args)
{
int[] a = {2,4,6,19,22,25};
int[] b = {7,13,14,21,23,33};
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the nth Biggest number to find: ");
int n = keyboard.nextInt();
int result = 0;
if (n < (a.length + b.length) / 2)
{
int ai = 0;
int bi = 0;
for (int i = n; i > 0; i--)
{
if (ai < a.length)
{
if (bi < b.length)
{
if (a[ai] > b[bi])
{
result = a[ai];
ai++;
}
else
{
result = b[bi];
bi++;
}
}
else
{
result = a[ai];
ai++;
}
}
else
{
if (bi < b.length)
{
result = b[bi];
bi++;
}
else
{
}
}
}
System.out.println(result);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.