Golang Program to Implement Median of Medians


The median is the element in the middle of a dataset when the dataset is sorted. The Median of Medians algorithm is a powerful technique that is used to find out the median element in an unsorted array. In this article, we will implement median of medians algorithm in golanguage, using two methods like the recursive method and the iterative method.

Explanation

The Median of Medians algorithm, an efficient technique for determining the median value in an unsorted array. It introduces two distinct methods: the recursive approach and the iterative approach.

Recursive Method: The findMedianRecursive function is introduced to compute the median recursively. If the array size is small (5 or fewer elements), it sorts and returns the middle value. For larger arrays, the function calculates subarray medians, selects the median of medians as a pivot, and partitions the array based on the pivot. The process recurs until the final median is identified.

Unsorted array: [9, 4, 7, 2, 8, 1, 6, 5, 3]
Sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output: 5

Iterative Method: The program offers the findMedianIterative function, which iteratively breaks down the array into subarrays of size 5. It computes subarray medians, updates the array with these medians, and iterates until the ultimate median is determined.

Algorithm

  • If the length of the array arr is less than or equal to 5, sort the array and return the middle element as the median. Divide the array arr into subarrays of size 5, except for the last subarray which may have fewer elements.

  • Recursively apply the Median of Medians algorithm on each subarray to find their medians. Find the median of the medians obtained in the previous step, which becomes the pivot element.

  • Partition the original array arr based on the pivot element, placing smaller elements to the left and larger elements to the right.

  • If the pivot element is at index k, compare k with the desired median index: If k is equal to the desired median index, return the pivot element as the median. If k is greater than the desired median index, recursively apply the Median of Medians algorithm on the left subarray.

  • If k is less than the desired median index, recursively apply the Median of Medians algorithm on the right subarray. Repeat the process until the desired median is found.

Syntax

func findMedianRecursive(arr []int) int

The syntax defines a function named findMedianRecursive that takes an integer slice arr as input. The function is designed to return an integer representing the median element.

func findMedianIterative(arr []int) int

The syntax declares a function named findMedianIterative that accepts an integer slice arr as an argument. By employing the Iterative Method of the Median of Medians algorithm, this function iteratively calculates and returns the median of the provided unsorted array.

Example

In this example, we will implement median of medians algorithm in golanguage using a recursive approach to find the median of an unsorted array, here we have an unsorted array arr with elements [9, 4, 7, 2, 8, 1, 6, 5, 3]. We call the findMedianRecursive function, passing the array as the input. The function applies the Recursive Method of the Median of Medians algorithm to find the median. The computed median is 5, which is then printed as output.

package main

import (
	"fmt"
	"sort"
)

func findMedianRecursive(arr []int) int {
	length := len(arr)

	if length <= 5 {
		sort.Ints(arr)
		return arr[length/2]
	}

	numGroups := length / 5
	if length%5 != 0 {
		numGroups++
	}

	medians := make([]int, numGroups)

	for i := 0; i < numGroups; i++ {
		start := i * 5
		end := start + 5
		if end > length {
			end = length
		}
		subarray := arr[start:end]
		medians[i] = findMedianRecursive(subarray)
	}

	pivot := findMedianRecursive(medians)

	left := make([]int, 0)
	right := make([]int, 0)
	equal := make([]int, 0)
	for _, num := range arr {
		if num < pivot {
			left = append(left, num)
		} else if num > pivot {
			right = append(right, num)
		} else {
			equal = append(equal, num)
		}
	}

	desiredIndex := len(left)

	if desiredIndex < len(left) {
		return findMedianRecursive(left)
	} else if desiredIndex >= len(left)+len(equal) {
		return findMedianRecursive(right)
	} else {
		return pivot
	}
}

func main() {
	arr := []int{9, 4, 7, 2, 8, 1, 6, 5, 3}
	median := findMedianRecursive(arr)
	fmt.Println("Median:", median)
}

Output

Median: 7

Example

In this Example,we will implement median of medians algorithm in golanguage using an iterative approach to find the median of an unsorted array, here we have an unsorted array [9, 4, 7, 2, 8, 1, 6, 5, 3]. By applying the Iterative Method of the Median of Medians algorithm, we calculate the median as 5. This approach involves dividing the array into subarrays, calculating their medians, and recursively narrowing down until the desired median is found.

package main

import (
	"fmt"
	"sort"
)

func findMedianIterative(arr []int) int {
	length := len(arr)

	for length > 5 {
		medians := make([]int, 0)
		numGroups := length / 5

		if length%5 != 0 {
			numGroups++
		}

		for i := 0; i < numGroups; i++ {
			start := i * 5
			end := start + 5
			if end > length {
				end = length
			}
			subarray := arr[start:end]
			sort.Ints(subarray)
			medians = append(medians, subarray[len(subarray)/2])
		}

		arr = medians
		length = len(arr)
	}

	sort.Ints(arr)
	return arr[length/2]
}

func main() {
	arr := []int{9, 4, 7, 2, 8, 1, 6, 5, 3}
	median := findMedianIterative(arr)
	fmt.Println("Median:", median)
}

Output

Median: 7

Real life implementation

Medical Diagnostics

In medical diagnosis, the median of medians algorithm can be used to find the median value of patient data, such as blood pressure readings or cholesterol levels. This helps doctors identify trends and make informed decisions, ensuring accurate assessments of patients' health conditions.

Financial Analysis

Financial analysts can apply the algorithm to large datasets of stock prices or economic indicators. This assists in determining median values, providing insights into market trends and stability, especially when outliers might distort results.

Conclusion

The Median of Medians algorithm is a powerful technique that can be very helpful in hospitals to find the median value of patient data and for financial analysts, to dataset. In this article we have looked at how we can implement median of medians algorithm in golanguage and find the median element in an unsorted array. Here we have worked on two methods: the recursive method and the iterative method. These methods provide efficient approaches to calculate the median with a time complexity of O(n).

Updated on: 07-Sep-2023

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements