Question
my code works for every test except the last one and I cant figure out why public static int[] removeLargest(int[] arr) if arr is null
my code works for every test except the last one and I cant figure out why
public static int[] removeLargest(int[] arr) if arr is null then return null; if arr is non-null then assume that arr contains at least one int value
otherwise, return an array that contains all the values stored in arr except for the largest value; if the largest value appears more than one time, then remove the first occurrence; the length of the returned array is arr.length 1.
Use the System.arraycopy method to copy values of arr into the returned array; if index is the location of the deleted value then copy values stored in indices 0 through index -1 and index + 1 through arr.length 1 to the returned array Example: Suppose arr = {9, -2, 3, 50, 4, 99, 11, 4, 5, 99, 3, 4, -6}; The method returns the following array {9, -2, 3, 50, 4, 11, 4, 5, 99, 3, 4, -6};
public static int[] removeLargest(int[] arr) {
int[] oneDim; if (arr == null) { oneDim = null;
} else { int length = arr.length - 1; oneDim = new int[length];
int index = 0; for (int i = 1; i < arr.length; i++) { if ( arr[index]< arr[i]) { index = i; } int tmp = arr[0]; arr[0] = arr[index]; // arr[0] contains the smallest value arr[index] = tmp; System.arraycopy(arr, 1, oneDim, 0, oneDim.length); } }
return oneDim; }
System.out.println(" Method 5: Test removeLargest: "); int[] arrFour = null; System.out.println("Result when array is null"); displayOneDimArr(hwTwo.removeLargest(arrFour)); arrFour = new int[] {100}; System.out.println("Result when array has exactly one value"); displayOneDimArr(hwTwo.removeLargest(arrFour)); arrFour = new int[]{100, 45, 22, 100, 9, 10}; System.out.println("Result when largest located at position zero"); displayOneDimArr(hwTwo.removeLargest(arrFour)); arrFour = new int[]{9, 100, 45, 22, 100, 9, 10001}; System.out.println("Result when largest located at the last position"); displayOneDimArr(hwTwo.removeLargest(arrFour)); arrFour = new int[]{9, 1, 45, 22, 100, 9, 100, 6, 100, 4, -4, 10}; System.out.println("Result when largest located in the middle of the array"); displayOneDimArr(hwTwo.removeLargest(arrFour));
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