How to find the middle of an ArrayList ?
+4
A:
If you have N
items, the middle item is usually defined as item at index N/2
(0-based).
10 items
0,1,2,3,4,5,6,7,8,9
|
5
13 items
0,1,2,3,4,5,6,7,8,9,0,1,2
|
6
Generally, if you need to find the middle of items between index low
(inclusive) and high
(exclusive), it's mathematically int mid = (low + high) / 2
. But due to arithmetic overflow in limited-precision integer, the proper formula is int mid = (low + high) >>> 1;
See also
- Google Research Blog post by Josh Bloch
polygenelubricants
2010-04-25 10:05:30
Wow, what a long answer on such a simple question. Where do you get courage?
Martijn Courteaux
2010-06-02 15:27:00
+1
A:
If the size of ArrayList is even in number, then use (ArrayList.size()/2)+1 or (ArrayList.size()/2) as the middle. If the size of ArrayList is odd in number, then use (ArrayList.size()+1)/2 as the middle.
Venkats
2010-04-25 10:18:19