generated from MIT-Emerging-Talent/Algorithms-And-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
admin
authored and
admin
committed
Jan 21, 2024
1 parent
2a52aa4
commit 6a3f39f
Showing
2 changed files
with
41 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
# Return the sorted array | ||
return arr |