Median of an unsorted array using Quick Select Algorithm | JAVA program to find median of an array ; Utility function to swapping of element ; Returns the correct position of pivot element ; Picks a random pivot element between l and r and partitions arr [ l . . r ] around the randomly picked element using partition ( ) ; Utility function to find median ; if l < r ; Find the partition index ; If partition index = k , then we found the median of odd number element in arr [ ] ; If index = k - 1 , then we get a & b as middle element of arr [ ] ; If partitionIndex >= k then find the index in first half of the arr [ ] ; If partitionIndex <= k then find the index in second half of the arr [ ] ; Function to find Median ; If n is odd ; If n is even ; Print the Median of arr [ ] ; Driver code
class GFG { static int a , b ; static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } static int Partition ( int arr [ ] , int l , int r ) { int lst = arr [ r ] , i = l , j = l ; while ( j < r ) { if ( arr [ j ] < lst ) { arr = swap ( arr , i , j ) ; i ++ ; } j ++ ; } arr = swap ( arr , i , r ) ; return i ; } static int randomPartition ( int arr [ ] , int l , int r ) { int n = r - l + 1 ; int pivot = ( int ) ( Math . random ( ) % n ) ; arr = swap ( arr , l + pivot , r ) ; return Partition ( arr , l , r ) ; } static int MedianUtil ( int arr [ ] , int l , int r , int k ) { if ( l <= r ) { int partitionIndex = randomPartition ( arr , l , r ) ; if ( partitionIndex == k ) { b = arr [ partitionIndex ] ; if ( a != - 1 ) return Integer . MIN_VALUE ; } else if ( partitionIndex == k - 1 ) { a = arr [ partitionIndex ] ; if ( b != - 1 ) return Integer . MIN_VALUE ; } if ( partitionIndex >= k ) return MedianUtil ( arr , l , partitionIndex - 1 , k ) ; else return MedianUtil ( arr , partitionIndex + 1 , r , k ) ; } return Integer . MIN_VALUE ; } static void findMedian ( int arr [ ] , int n ) { int ans ; a = - 1 ; b = - 1 ; if ( n % 2 == 1 ) { MedianUtil ( arr , 0 , n - 1 , n / 2 ) ; ans = b ; } else { MedianUtil ( arr , 0 , n - 1 , n / 2 ) ; ans = ( a + b ) / 2 ; } System . out . print ( " Median ▁ = ▁ " + ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 3 , 5 , 7 , 4 , 19 , 26 } ; int n = arr . length ; findMedian ( arr , n ) ; } }