Median of difference of all pairs from an Array | Java program to implement the above approach ; Function check if mid can be median index of the difference array ; Size of the array ; Total possible no of pair possible ; The index of the element in the difference of all pairs from the array ; Count the number of pairs having difference <= mid ; If the difference between end and first element is less then or equal to mid ; Checking for the no of element less than or equal to mid is greater than median or not ; Function to calculate the median of differences of all pairs from the array ; Size of the array ; Initialising the low and high ; Binary search ; Calculate mid ; If mid can be the median of the array ; Returning the median of the differences of pairs from the array ; Driver code
import java . util . * ; class GFG { static boolean possible ( long mid , int [ ] a ) { long n = a . length ; long total = ( n * ( n - 1 ) ) / 2 ; long need = ( total + 1 ) / 2 ; long count = 0 ; long start = 0 , end = 1 ; while ( end < n ) { if ( a [ ( int ) end ] - a [ ( int ) start ] <= mid ) { end ++ ; } else { count += ( end - start - 1 ) ; start ++ ; } } if ( end == n && start < end && a [ ( int ) end - 1 ] - a [ ( int ) start ] <= mid ) { long t = end - start - 1 ; count += ( t * ( t + 1 ) / 2 ) ; } if ( count >= need ) return true ; else return false ; } static long findMedian ( int [ ] a ) { long n = a . length ; long low = 0 , high = a [ ( int ) n - 1 ] - a [ 0 ] ; while ( low <= high ) { long mid = ( low + high ) / 2 ; if ( possible ( mid , a ) ) high = mid - 1 ; else low = mid + 1 ; } return high + 1 ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 7 , 5 , 2 } ; Arrays . sort ( a ) ; System . out . println ( findMedian ( a ) ) ; } }