Skip to content

Commit 11e68e4

Browse files
authored
Added Insertion Sort (DhanushNehru#171)
1 parent ce5cee1 commit 11e68e4

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Sorting/insertionsort.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def insertionSort(arr):
2+
n = len(arr) # Get the length of the array
3+
4+
if n <= 1:
5+
return # If the array has 0 or 1 element, it is already sorted, so return
6+
7+
for i in range(1, n): # Iterate over the array starting from the second element
8+
key = arr[i] # Store the current element as the key to be inserted in the right position
9+
j = i-1
10+
while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead
11+
arr[j+1] = arr[j] # Shift elements to the right
12+
j -= 1
13+
arr[j+1] = key # Insert the key in the correct position
14+
15+
# Sorting the array [12, 11, 13, 5, 6] using insertionSort
16+
arr = [12, 11, 13, 5, 6]
17+
insertionSort(arr)
18+
print(arr)

0 commit comments

Comments
 (0)