Median of Two Sorted Arrays in TypeScript

// A function that takes two sorted arrays of numbers and returns the median of the two arrays
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
  // Get the lengths of the two arrays
  let m = nums1.length;
  let n = nums2.length;

  // If the first array is longer than the second, swap them
  if (m > n) {
    [nums1, nums2] = [nums2, nums1];
    [m, n] = [n, m];
  }

  // Initialize the binary search variables
  let iMin = 0; // The minimum index of the first array
  let iMax = m; // The maximum index of the first array
  let halfLen = Math.floor((m + n + 1) / 2); // The half length of the merged array

  // Perform binary search to find the partition point of the two arrays
  while (iMin <= iMax) {
    // The partition index of the first array
    let i = Math.floor((iMin + iMax) / 2);
    // The partition index of the second array
    let j = halfLen - i;

    // If the left element of the first array is too small, move the partition to the right
    if (i < iMax && nums2[j - 1] > nums1[i]) {
      iMin = i + 1;
    }
    // If the left element of the first array is too large, move the partition to the left
    else if (i > iMin && nums1[i - 1] > nums2[j]) {
      iMax = i - 1;
    }
    // Otherwise, we have found the correct partition
    else {
      // The maximum left element of the merged array
      let maxLeft = 0;
      // If the first array has no left element, use the second array's left element
      if (i == 0) {
        maxLeft = nums2[j - 1];
      }
      // If the second array has no left element, use the first array's left element
      else if (j == 0) {
        maxLeft = nums1[i - 1];
      }
      // Otherwise, use the larger of the two left elements
      else {
        maxLeft = Math.max(nums1[i - 1], nums2[j - 1]);
      }

      // If the total length of the merged array is odd, return the maximum left element as the median
      if ((m + n) % 2 == 1) {
        return maxLeft;
      }

      // The minimum right element of the merged array
      let minRight = 0;
      // If the first array has no right element, use the second array's right element
      if (i == m) {
        minRight = nums2[j];
      }
      // If the second array has no right element, use the first array's right element
      else if (j == n) {
        minRight = nums1[i];
      }
      // Otherwise, use the smaller of the two right elements
      else {
        minRight = Math.min(nums1[i], nums2[j]);
      }

      // If the total length of the merged array is even, return the average of the maximum left and minimum right elements as the median
      return (maxLeft + minRight) / 2;
    }
  }

  // If the binary search fails, return 0 as a default value
  return 0;
}

Next