'Finding the middle element(s) of an array in Java
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;
}
Solution 1:[1]
int mid = firstIndex + (lastIndex-firstIndex)/2
, will give you the mid of the array.
Solution 2:[2]
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.
Solution 3:[3]
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();
}
}
Solution 4:[4]
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]
Solution 5:[5]
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);
Solution 6:[6]
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
Solution 7:[7]
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;
}
Solution 8:[8]
int arr[] = {10, 11, 12, 13, 15, 18, 20};
int num = (arr.length) / 2;
if (num % 2 == 0) {
for (int i = (num - 1); i <= num; i++) {
System.out.println(arr[i]);
}
} else {
System.out.println(arr[num]);
}
Solution 9:[9]
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]);
}
}
}
Solution 10:[10]
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]));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow