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.
-
8Using the division operator on an array wouldn't split it anyway... – Brendan Lesniak Feb 14 '15 at 20:25
-
3You mean you don't want to use some thing like array.length / 2 to determine the mid point? – MadProgrammer Feb 14 '15 at 20:26
-
4You could use bitshifts; shifting one position to the right is equivalent to division by two. – DennisW Feb 14 '15 at 20:29
-
http://stackoverflow.com/questions/5386377/division-without-using – Tarik Feb 14 '15 at 20:49
-
use the shift operators.i.e. >> operator – Rusheel Jain Feb 14 '15 at 21:06
2 Answers
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.

- 7,260
- 4
- 30
- 47
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.

- 40,677
- 6
- 91
- 113