Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
public final class MedianOfRunningArrayInteger extends MedianOfRunningArray<Integer> {
@Override
public Integer calculateAverage(final Integer a, final Integer b) {
return (a + b) / 2;
// Widen to long so that summing values near Integer.MAX_VALUE does not overflow.
final long sum = (long) a + b;
return (int) (sum / 2);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.thealgorithms.misc;

import java.math.BigInteger;

public final class MedianOfRunningArrayLong extends MedianOfRunningArray<Long> {
@Override
public Long calculateAverage(final Long a, final Long b) {
return (a + b) / 2L;
// a + b overflows a long near its bounds and there is no wider primitive to widen to.
return BigInteger.valueOf(a).add(BigInteger.valueOf(b)).divide(BigInteger.TWO).longValueExact();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,42 @@ public void testWithLongValues() {
assertEquals(46116860244273878L, stream.getMedian());
}

@Test
public void testWithIntegerValuesNearMaxValue() {
var stream = new MedianOfRunningArrayInteger();
stream.insert(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, stream.getMedian());
stream.insert(Integer.MAX_VALUE - 2);
assertEquals(Integer.MAX_VALUE - 1, stream.getMedian());
stream.insert(2000000000);
assertEquals(Integer.MAX_VALUE - 2, stream.getMedian());
}

@Test
public void testWithIntegerValuesNearMinValue() {
var stream = new MedianOfRunningArrayInteger();
stream.insert(Integer.MIN_VALUE);
stream.insert(Integer.MIN_VALUE + 2);
assertEquals(Integer.MIN_VALUE + 1, stream.getMedian());
}

@Test
public void testWithLongValuesNearMaxValue() {
var stream = new MedianOfRunningArrayLong();
stream.insert(Long.MAX_VALUE);
assertEquals(Long.MAX_VALUE, stream.getMedian());
stream.insert(Long.MAX_VALUE - 2);
assertEquals(Long.MAX_VALUE - 1, stream.getMedian());
}

@Test
public void testWithLongValuesNearMinValue() {
var stream = new MedianOfRunningArrayLong();
stream.insert(Long.MIN_VALUE);
stream.insert(Long.MIN_VALUE + 2);
assertEquals(Long.MIN_VALUE + 1, stream.getMedian());
}

@Test
public void testWithDoubleValues() {
var stream = new MedianOfRunningArrayDouble();
Expand Down
Loading