{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Array Reversal: O(n / 2)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr = [1, 2, 3, 4, 5, 6]\n", "arr" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[6, 5, 4, 3, 2, 1]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr.reverse() # Inplace\n", "arr" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr[::-1] # Not Inplace" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[6, 5, 4, 3, 2, 1]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iterative" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def reverseArr(arr):\n", " start, end = 0, len(arr) - 1\n", " \n", " while start < end:\n", " arr[start], arr[end] = arr[end], arr[start]\n", " \n", " start += 1\n", " end -= 1" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "reverseArr(arr)\n", "arr" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Recursive" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def recursiveReverseArr(arr, start, end):\n", " if start >= end:\n", " return\n", " \n", " arr[start], arr[end] = arr[end], arr[start]\n", " \n", " recursiveReverseArr(arr, start + 1, end - 1)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[6, 5, 4, 3, 2, 1]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "recursiveReverseArr(arr, 0, len(arr) - 1)\n", "arr" ] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }