0

I am wondering if there is a way to divide an array into two without the division operator? For the task that I'm doing I can't use / or double. I know the size of the array and I know I could set the size of the two sub arrays to half of the original array but I just wondering if there's a way without hardcoding it. Thank you.

2 Answers2

3

Assuming that you want to find the middle index of an array without using the division operator and you by "use / or double" mean that you can't use floating point values (so multiplying with 0.5 is out of the question).

You can look into the bit-shift operators. An example:

int[] myArray = new int[128];
int middleIndex = myArray.length >> 1; // middleIndex is now 64
middleIndex = middleIndex >> 1;        // 32

Shifting the bits of an integer one position to the right is equivalent to dividing by two.

MAV
  • 7,260
  • 4
  • 30
  • 47
0

You can find the middle of the array by setting one variable to zero and another to the end of the array and then in a loop increment one and decrement the other until they meet or cross.

If your array has an odd length, they will eventually be equal, and that will be the index of the middle element of the array.

If your array has an even length, they will differ by one, and mark the middle two elements of the array.

Don Roby
  • 40,677
  • 6
  • 91
  • 113