Skip to content

Commit d65eeb5

Browse files
committed
add insertion sort
1 parent 0ee486b commit d65eeb5

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ This is my study repository.
1515
* recursion.
1616
* bubble sort.
1717
* selection sort.
18-
18+
* insertion sort.
1919

2020
## Link
2121

src/insertion_sort.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env python3
2+
3+
##
4+
# Insertion Sort
5+
##
6+
7+
8+
import numpy as np
9+
10+
def insertion_sort(array):
11+
"""
12+
Sorts an array using the insertion sort algorithm.
13+
14+
The insertion sort algorithm builds the final sorted array one item at a time.
15+
It repeatedly picks the next element and inserts it into its correct position
16+
among the already sorted elements.
17+
18+
Parameters:
19+
array (numpy.ndarray): The array to be sorted.
20+
21+
Returns:
22+
numpy.ndarray: The sorted array.
23+
"""
24+
n = len(array) # Get the length of the array
25+
26+
# Loop through each element starting from the second one
27+
for i in range(1, n):
28+
marked = array[i] # Store the element to be inserted
29+
30+
j = i - 1 # Start comparing with the previous element
31+
# Shift elements to the right to make space for the marked element
32+
while j >= 0 and marked < array[j]:
33+
array[j + 1] = array[j] # Shift the element to the right
34+
j -= 1 # Move to the previous element
35+
36+
# Insert the marked element at its correct position
37+
array[j + 1] = marked
38+
39+
return array # Return the sorted array
40+
41+
# Example usage of the insertion_sort function
42+
sorted_array = insertion_sort(np.array([15, 34, 8, 3]))
43+
print("Sorted array:", sorted_array) # Output: [ 3 8 15 34]

0 commit comments

Comments
 (0)