Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the middle element(s) of an array in Java

Tags:

java

arrays

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;
}
like image 747
user5183901 Avatar asked Aug 03 '15 01:08

user5183901


People also ask

How do you find the median of an array in Java?

First, simply sort the array. Then, check if the number of elements present in the array is even or odd. If odd, then simply return the mid value of the array. Else, the median is the average of the two middle values.

How do you find the middle element of an array if you don't know the size of an array?

The statement array[(int)((array. length-1)/2)] will return the middle value, rounding down.

How can you find middle element of an array without using length?

one way you can find midpoint of array is (for odd length array) just use two loops ,1st loop start traverse from 0 index and the other (nested) loop will traverse from last index of array. Now just compare elements when it comes same ...that will be the mid point of array. i.e if(arr[i]== arr[j]) .


2 Answers

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

like image 70
Shashikant Sharma Avatar answered Sep 17 '22 15:09

Shashikant Sharma


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();
    }
}
like image 23
Ryan Avatar answered Sep 16 '22 15:09

Ryan