From 6a3f39f9cf416b71e741d1591ffac1f791536dc7 Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 21 Jan 2024 22:07:10 +0430 Subject: [PATCH] README File added --- src/sorting/python/insertion_sort/README.md | 18 ++++++++++++++ .../insertion_sort/src/insertion_sort.py | 24 ++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/sorting/python/insertion_sort/README.md b/src/sorting/python/insertion_sort/README.md index e69de29..f9cab08 100644 --- a/src/sorting/python/insertion_sort/README.md +++ b/src/sorting/python/insertion_sort/README.md @@ -0,0 +1,18 @@ +# Insertion Sort + +## Overview +This Python module provides an implementation of the insertion sort algorithm. The `insertionsort_v1` function takes an input array and sorts it in ascending order using the insertion sort algorithm. + +## Installation +No installation is required for this module. Simply include the `insertionsort.py` file in your project. + +## Usage + +```python +from insertionsort import insertionsort_v1 + + +# Example +arr = [4, 2, 1, 3, 5] +sorted_arr = insertionsort_v1(arr) +print(sorted_arr) # Output: [1, 2, 3, 4, 5] \ No newline at end of file diff --git a/src/sorting/python/insertion_sort/src/insertion_sort.py b/src/sorting/python/insertion_sort/src/insertion_sort.py index cedb41c..bb19864 100644 --- a/src/sorting/python/insertion_sort/src/insertion_sort.py +++ b/src/sorting/python/insertion_sort/src/insertion_sort.py @@ -1,10 +1,32 @@ def insertionsort_v1(arr): + """ + Sorts the input array using the insertion sort algorithm. + Args: + arr (List[int]): The input array to be sorted. + Returns: + List[int]: The sorted array in ascending order. + """ + for i in range(1, len(arr)): + # Select the current element to be inserted at the correct position key = arr[i] j = i - 1 + # Initialize the index of the previous element + j = i - 1 + + # Move elements greater than the key to the right while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key + # Shift the element to the right + arr[j + 1] = arr[j] + # Move to the previous element + j -= 1 + + return arr + # Insert the key at the correct position + arr[j + 1] = key - return arr \ No newline at end of file + # Return the sorted array + return arr \ No newline at end of file