14

Given an array of integers, I need to return a new array containing the middle element(s) from the original array. Specifically, the result will have one element if the length of the original array is odd, and two elements if it's even.

This is my code right now, which works for arrays of even length. How do I make it work for arrays with odd length?

public int[] makeMiddle(int[] nums) {
    int[] a = new int[2];
    if(nums.length>1) {
        a[1]=nums[nums.length/2];
        a[0]=nums[nums.length/2-1];
        return a;
    } else {
        a[2]=nums[((nums.length+1)/2) -1];
    }
    return a;
}
APerson
  • 8,140
  • 8
  • 35
  • 49
user5183901
  • 159
  • 1
  • 1
  • 6
  • 2
    [Finding the median value of an array?](http://stackoverflow.com/questions/3691940/finding-the-median-value-of-an-array) should help you forward. – Mick Mnemonic Aug 03 '15 at 01:40
  • For the odd array, I need the middle element. For example: if I have: a = {1,2,3,4,5}, the result for it will be: {3}. The problem is that I don't know how to establish a general loop for odd length that will give me the single element that is right in the middle – user5183901 Aug 03 '15 at 01:51
  • Please review the answer given below, thanks. – Tim Biegeleisen Aug 04 '15 at 06:08

9 Answers9

30

int mid = firstIndex + (lastIndex-firstIndex)/2 , will give you the mid of the array.

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
9

start + (end - start) / 2 is prefered over (start + end) / 2. In case of using (start + end) / 2 and the summation result of start + end is larger than the integer max value, this will cause overflow.

public class MidOfArray {
    static final int start = Integer.MAX_VALUE;
    static final int end = Integer.MAX_VALUE;

    public static void doesnotWork() {
        int mid = (start + end) / 2;
        System.out.println(mid);    // output: -1
    }
    public static void worksGreat() {
        int mid = start + ((end + start) / 2);
        System.out.println(mid);    // output: 2147483646
    }
    public static void main(String[] args) {
        doesnotWork();
        worksGreat();
    }
}
Ryan
  • 192
  • 2
  • 4
5

Try this code:

public int[] makeMiddle(int[] nums) {
    int[] a;
    if (nums.length %2 == 0) {
        // even-length array (two middle elements)
        a = new int[2];
        a[0] = nums[(nums.length/2) - 1];
        a[1] = nums[nums.length/2];
    } else {
        // odd-length array (only one middle element)
        a = new int[1];
        a[0] = nums[nums.length/2];
    }
    return a;
}

In your original code, you were not checking whether the length of nums be even or odd.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

A slightly general solution:

public static int[] midArray(int[] arr) {
    int extra = arr.length % 2 == 0? 1 : 0;

    int[] a = new int[1 + extra];

    int startIndex = arr.length / 2 - extra;
    int endIndex = arr.length / 2;

    for (int i = 0; i <= endIndex - startIndex; i++) {
        a[i] = arr[startIndex + i];
    }

    return a;

}

Test run:

public static void main(String[] args) {
    int[] a = new int[]{1, 2, 3, 4};
    int[] b = new int[]{1, 2, 3};
    int[] c = new int[]{1, 2};
    int[] d = new int[]{1};

    System.out.println(Arrays.toString(midArray(a)));
    System.out.println(Arrays.toString(midArray(b)));
    System.out.println(Arrays.toString(midArray(c)));
    System.out.println(Arrays.toString(midArray(d)));

}

Output:

[2, 3]
[2]
[1, 2]
[1]
Bijay Gurung
  • 1,094
  • 8
  • 12
1

I was going through Java Array docs and found that. It is perfect solution to get mid of an array.

int low = startIndexOfArray;      // 0 Normally but can be anything
int high = endIndexOfArray - 1;       

int mid = (low + high) >>> 1;
System.out.print("Mid Value OF Array Is "+ mid);
Kunal Vohra
  • 2,703
  • 2
  • 15
  • 33
1

Maybe this will help you

const median = arr => {
  const mid = Math.floor(arr.length / 2),
    nums = [...arr].sort((a, b) => a - b);
  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
console.log(median([5, 6, 50, 1, -5]));
console.log(median([1, 2, 3, 4, 5]));
0

I've seen:

Integer midElement(int[] ary, int start, int end) {
    if (start < end) {
        return null;
    }
    int mid = (start + end)/2;
    return ary[mid];

The above works for any start index and any end index. It even checks that invalid inputs were not passed it. The book Cracking The Coding Interview uses this approach throughout the book in the various relevant problems

Jose Quijada
  • 558
  • 6
  • 13
0
public int[] makeMiddle(int[] nums) {


        if(nums.length>=2){

        if(nums[nums.length-1]%2==0) {  
          int[] arrEven=new int[2];
          arrEven[0]=nums[(nums.length/2)-1];
          arrEven[1]=nums[(nums.length/2)];
          return arrEven;                                                
         }
        else {              
            int[] arrOdd=new int[1];
            arrOdd[0]=nums[(nums.length/2)];                
            return arrOdd;
        }
        }
        return nums;
 }
Rares
  • 1
  • 2
0

Try it like this:

class MiddleArray {

    public static void main(String[] args) {
        int arr[] = {100, 14, 46, 47, 96, 94};
        int totalLength = arr.length / 2;
        System.out.println("Total Length of Array :" + arr.length + "\n");
        if (arr.length % 2 == 0) {
            System.out.println("Middle Element of array :" + arr[totalLength] + "  " + arr[totalLength - 1]);
        } else {
            System.out.println("Array Postion:" + arr[totalLength]);
        }
    }
}
MWiesner
  • 8,868
  • 11
  • 36
  • 70
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 16 '22 at 17:44