Finding median index of array in JavaScript


Understanding the intricacies of finding the median index of an array in JavaScript holds profound significance for developers seeking to unravel the mysteries of data manipulation. The median, a statistical measure of central tendency, provides valuable insights into the distribution and balance of a dataset. With JavaScript's versatile capabilities, harnessing the power of algorithms to pinpoint the median index of an array unveils a realm of possibilities for analyzing and extracting valuable information from complex datasets. In this article, we embark on a journey to explore the step-by-step process of determining the median index of an array in JavaScript, delving into the lesser-known techniques and functions that empower developers to unlock the hidden gems within their data arrays.

Problem Statement

Create a JavaScript algorithm to find the index of the median value in an unsorted array of integers. For arrays with odd length, the median is the element at the middle index. For even-length arrays, the median is the element closest to the mean of the two central elements. The algorithm should handle arrays of any size efficiently and have optimal time complexity to find the desired index.

Sample Input −

Array: [7, 12, 5, 3, 9, 2, 15, 8]

Sample Output −

Index of the element closest to the median: 4 

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Sorting Approach

  • QuickSelect Algorithm

  • Median of Medians Approach

  • Counting Sort Algorithm

Method 1: Sorting Approach

To find the index of the element closest to the median in an unsorted array, we follow a sorting approach. First, we calculate the median index by dividing the array length by 2. Using a helper function called calculateMedian, we sort the array and determine the median based on its length. Then, we initialize variables closestIndex and minDiff. Starting from index 1, we iterate through the array, comparing each element's absolute difference with the median to the current minimum difference. If the difference is smaller, we update closestIndex and minDiff. Finally, we return closestIndex, representing the index of the element closest to the median. The approach considers absolute differences, ensuring proximity regardless of element size.

Example

The given code consists of three functions: findMedianValue, calculateMedian, and findIndex. findMedianValue finds the element closest to the median value in an array by using calculateMedian and iterating through the array. calculateMedian sorts the array and calculates the middle element(s) to determine the median value. findIndex finds the index of a given element in an array. In the code, an array is defined, and findMedianValue is used to find the median element, which is then used with findIndex to determine its index. The results are printed to the console.

function findMedianValue(arr) { 
   const median = calculateMedian(arr); 
   let medianElement = 0; 
   let minDiff = Math.abs(arr[0] - median); 
   for (let i = 1; i < arr.length; i++) { 
      const diff = Math.abs(arr[i] - median); 
      if (diff < minDiff) { 
         minDiff = diff; 
         medianElement = arr[i]; 
      } 
   } 
   return medianElement; 
} 
function calculateMedian(arr) { 
   const sortedArr = arr.slice().sort((a, b) => a - b); 
   const length = sortedArr.length;
   if (length % 2 === 0) { 
      const middle = length / 2; 
      return (sortedArr[middle - 1] + sortedArr[middle]) / 2; 
   } else { 
      const middle = Math.floor(length / 2); 
      return sortedArr[middle]; 
   } 
} 
function findIndex(arr,el){ 
   let n=arr.length; 
   for(let i=0;i<n;i++){ 
      if(arr[i]==el) 
      return i; 
   } 
   return -1; 
} 
const arr = [1, 7, 3, 6, 5, 6]; 
const medianElement=findMedianValue(arr); 
const medianIndex=findIndex(arr,medianElement); 
console.log("Median element index:", medianIndex);  
console.log("Median element:", medianElement);

Output

The following is the console output −

Median element index: 3
Median element: 6

Method 2: Quickselect Algorithm

To find the index of the median element in an unsorted array in JavaScript, we can use the quickselect algorithm. This involves defining a quickselect function that recursively partitions the array until the desired element is found. We select a pivot element, rearrange the array based on the pivot, and compare the pivot index with the desired index. If they match, we return the index. If the pivot index is greater, we recursively call quickselect on the left subarray; if it's smaller, we call it on the right subarray. This process continues until the desired element is located. The algorithm has a time complexity of O(n), making it an efficient solution for finding the median or the element closest to it in an unsorted array.

Example

The given code includes functions to find the median of an array and determine the index of the closest element to the median. The "partition" function selects a pivot element and rearranges the array. "quickSelect" recursively finds the kth smallest element. "findClosestToMedian" calculates the median, iterates through the array, and updates the closest element. "findIndex" iterates through the array to find the index of a given element. In the example usage, the closest element to the median is found using "findClosestToMedian" and its index is found using "findIndex," then printed to the console.

function partition(arr, low, high) { 
   const pivot = arr[high]; 
   let i = low - 1; 
   for (let j = low; j < high; j++) { 
      if (arr[j] <= pivot) { 
         i++; 
         [arr[i], arr[j]] = [arr[j], arr[i]]; 
      } 
   } 
   [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; 
   return i + 1; 
} 
function quickSelect(arr, low, high, k) { 
   if (low === high) { 
      return arr[low]; 
   } 
   const pivotIndex = partition(arr, low, high); 
   if (k === pivotIndex) { 
      return arr[k]; 
   } else if (k < pivotIndex) { 
      return quickSelect(arr, low, pivotIndex - 1, k); 
   } else { 
      return quickSelect(arr, pivotIndex + 1, high, k); 
   } 
} 
function findClosestToMedian(arr) { 
   const n = arr.length; 
   const medianIndex = Math.floor(n / 2); 
   const median = quickSelect(arr, 0, n - 1, medianIndex); 
   let closestValue=0
   let closestDiff = Math.abs(arr[0] - median); 
   for (let i = 1; i < n; i++) { 
   const diff = Math.abs(arr[i] - median); 
      if (diff < closestDiff) { 
         closestDiff = diff; 
         closestValue=arr[i];
      } 
   } 
   return closestValue; 
} 

function findIndex(arr,el){
   let n=arr.length;
   for(let i=0;i<n;i++){
      if(arr[i]==el)
      return i;
   }
   return -1;
}

// Example usage: 
const array = [5, 10, 2, 8, 3, 6]; 
const arrayCopy=JSON.parse(JSON.stringify(array));
const medianElement = findClosestToMedian(array);
const medianIndex=findIndex(arrayCopy,medianElement);
console.log("Median element index:", medianIndex); 
console.log("Median element:", medianElement);

Output

The following is the console output −

Median element index: 5
Median element: 6

Method 3: Median of Medians

To find the median or element closest to the median of an unsorted array using the median of medians algorithm in JavaScript, follow these steps. Firstly, define the main function, findMedianIndex, and handle cases where the array is empty or contains only one element. Calculate the median index as the floor value of the array length divided by 2. Create a partition helper function that recursively applies the median of medians algorithm to find the pivot index. Use the pivot index to partition the array into two subarrays. Determine which subarray to continue the search based on the median index, updating the start or end index accordingly. Finally, call the findMedianIndex function on the array to get the desired index.

Example

The findMedian function uses helper functions to find the median element of an array. The swap function swaps elements, the partition function partitions the array around a pivot element, and the findMedianOfMedians function recursively finds the median of medians. The findMedian function calculates the median index and returns the median element. In the example usage, the findMedian and findIndex functions are called on an array and its copy to find the median element and its index, respectively, with the results logged to the console.

function findMedian(arr) { 

   // Helper function to swap two elements in the array 
   function swap(arr, i, j) { 
      const temp = arr[i]; 
      arr[i] = arr[j]; 
      arr[j] = temp; 
   } 

   // Helper function to partition the array around the pivot 
   function partition(arr, left, right, pivotIndex) { 
      const pivotValue = arr[pivotIndex]; 
      let partitionIndex = left; 

      // Move the pivot to the rightmost position 
      swap(arr, pivotIndex, right); 

      for (let i = left; i < right; i++) { 
         if (arr[i] < pivotValue) { 
            swap(arr, i, partitionIndex); 
            partitionIndex++; 
         } 
      } 
      // Move the pivot back to its final position 
      swap(arr, partitionIndex, right); 
      return partitionIndex; 
   } 

   // Helper function to find the median of medians recursively 
   function findMedianOfMedians(arr, left, right, targetIndex) { 
      // If the array is small, find the median directly 
      if (right - left < 5) { 
         arr = arr.slice(left, right + 1).sort((a, b) => a - b); 
         return left + Math.floor((right - left) / 2); 
      } 

      // Divide the array into groups of size 5 and find the median of each group 
      for (let i = left; i <= right; i += 5) { 
         const groupRight = Math.min(i + 4, right); 
         const medianIndex = findMedianOfMedians(arr, i, groupRight, Math.floor((groupRight - i) / 2)); 
         swap(arr, medianIndex, left + Math.floor((i - left) / 5)); 
      } 

      // Find the median of medians recursively 
      const medianOfMediansIndex = findMedianOfMedians(arr, left, left + Math.ceil((right - left) / 5) - 1, Math.floor((right - left) / 10)); 

      // Partition the array around the median of medians 
      const pivotIndex = partition(arr, left, right, medianOfMediansIndex); 

      // Compare the pivot index with the target index 
      if (pivotIndex === targetIndex) { 
         return pivotIndex; 
      } else if (targetIndex < pivotIndex) { 
         return findMedianOfMedians(arr, left, pivotIndex - 1, targetIndex); 
      } else { 
         return findMedianOfMedians(arr, pivotIndex + 1, right, targetIndex);
      } 

   } 

   // Calculate the median index based on the array length 
   const medianIndex = Math.floor((arr.length - 1) / 2); 
   // Find the index of the median element using the Median of Median algorithm 
   const medianElementIndex = findMedianOfMedians(arr, 0, arr.length - 1, medianIndex); 
   return arr[medianElementIndex];
   return medianElementIndex; 
} 

function findIndex(arr,el){ 
   let n=arr.length; 
   for(let i=0;i<n;i++){ 
      if(arr[i]==el) 
      return i; 
   } 
   return -1; 
} 

// Example usage: 
const array = [7, 2, 9, 4, 5, 6, 1, 3, 8];
const arrayCopy=JSON.parse(JSON.stringify(array)); 
const medianElement = findMedian(array); 
const medianIndex=findIndex(arrayCopy,medianElement); 
console.log("Median element index:", medianIndex);  
console.log("Median element:", medianElement);

Output

The following is the console output −

Median element index: 5
Median element: 6

Method 4: Counting Sort

To find the index of the median element in an unsorted array using the counting sort algorithm in JavaScript, follow these steps: initialize a counting array with the length of the maximum element plus one, increment the count of each element in the counting array, modify the counting array by calculating cumulative frequencies, determine the median index based on the array length, traverse the counting array to find the cumulative sum that exceeds or equals the median index, and return the index of the element found as the median index. This approach efficiently handles small, known input value ranges, and has a time complexity of O(n+k), where n is the array length and k is the range of values.

Example

The provided code implements counting sort to determine the median of an array. It finds the maximum and minimum values, initializes a countArray, and increments counts based on the minimum value. Another loop finds the median by comparing running counts. The index plus the minimum value represents the median. The code also includes a findIndex function. It demonstrates usage by defining an example array, creating a deep copy, and finding the median and its index. Results are printed to the console.

function findMedian(arr) {
   // Counting Sort
   const max = Math.max(...arr);
   const min = Math.min(...arr);
   const countArray = Array(max - min + 1).fill(0);
   for (let i = 0; i < arr.length; i++) {
      countArray[arr[i] - min]++;
   }
   let sum = 0;
   for (let i = 0; i < countArray.length; i++) {
      sum += countArray[i];
      if (sum >= Math.ceil(arr.length / 2)) {
         return i + min; // Value at the median index
      }
   }
}
function findIndex(arr,el){ 
   let n=arr.length ;
   for(let i=0;i<n;i++){ 
      if(arr[i]==el) 
      return i; 
   } 
   return -1; 
} 

// Example usage:
const array = [7, 2, 5, 1, 8, 4];
const arrayCopy=JSON.parse(JSON.stringify(array)); 
const medianElement = findMedian(array);
const medianIndex=findIndex(arrayCopy,medianElement); 
console.log("Median element index:", medianIndex);  
console.log("Median element:", medianElement);

Output

The following is the console output −

Median element index: 5
Median element: 4

Conclusion

In denouement, the quest for locating the median index of an array in JavaScript unveils an intricate yet intriguing challenge. The elucidation lies within an esoteric realm of algorithms and computations, requiring a sagacious approach to achieve precision. By employing seldom-utilized methods and leveraging the obscure depths of JavaScript, one can uncover the elusive median index, enriching the realm of data manipulation and analysis. In closing, this arcane endeavor illuminates the boundless possibilities of JavaScript, beckoning intrepid programmers to embrace the uncharted territories of array exploration and unveil the enigma of the median index.

Updated on: 04-Aug-2023

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements