{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Median of Two Sorted Arrays - Divide & Conquer - O(logn)\n", "1. Both arrays are of same length" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def median(arr):\n", " l = len(arr)\n", " mid = int(l / 2)\n", " \n", " if l % 2 == 0:\n", " return (arr[mid - 1] + arr[mid]) / 2\n", " else:\n", " return arr[mid]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def findMedianForArrays(arr1, arr2):\n", " n = len(arr1) if len(arr1) == len(arr2) else 0\n", " \n", " if n <= 0:\n", " return -1\n", " if n == 1:\n", " return (arr1[0] + arr2[0]) / 2\n", " if n == 2:\n", " return (max(arr1[0], arr2[0]) + min(arr1[1], arr2[1])) / 2\n", "\n", " m1 = median(arr1)\n", " m2 = median(arr2)\n", " \n", " if m1 == m2:\n", " return m1\n", " \n", " mid = int(n / 2)\n", " \n", " if m1 < m2:\n", " return findMedianForArrays(arr1[mid:], arr2[:mid + 1])\n", " else:\n", " return findMedianForArrays(arr1[:mid + 1], arr2[mid:])" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "16.0" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr1 = [1, 12, 15, 26, 38]\n", "arr2 = [2, 13, 17, 30, 45]\n", "\n", "findMedianForArrays(arr1, arr2)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" } }, "nbformat": 4, "nbformat_minor": 2 }