Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c370925

Browse files
committed
Insertion Sort
1 parent a625179 commit c370925

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def insertion_Sort(A):
2+
"""Sort list of comparable elements into ascending order"""
3+
4+
for k in range(1, len(A)):
5+
curr=A[k] #current element to be inserted
6+
j=k #find correct index j for current
7+
#while A[j-1] > than curr (A[j]) we swap leftwards until A[j-1] <curr
8+
while j >0 and A[j-1]>curr: #element A[j-1] must be after current
9+
A[j]=A[j-1]
10+
j-=1
11+
A[j]=curr #current is now in the right place
12+
13+
return A
14+
15+
list=[2,1,5,3,7,8,4]
16+
print(insertion_Sort(list))

PythonDataStructsAndAlgo/Notes.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,13 @@
133133

134134
> The analysis for many behaviors is quite intuitive. Methods that produce a new string require time that is linear in the length of the string that is produced, since a string is an array of characters.
135135
136-
> Many of the behaviours that test boolean conditions of a string take O(n) time, examining all n characters in the worst case, but short circuiting as soon as the answer becomes evident. Such as checking if string is lower character and the first character is upper cased which gives automatically the reuslt False.
136+
> Many of the behaviours that test boolean conditions of a string take O(n) time, examining all n characters in the worst case, but short circuiting as soon as the answer becomes evident. Such as checking if string is lower character and the first character is upper cased which gives automatically the reuslt False.
137+
138+
### Insertion Sort
139+
> Explanation: Starting with the first element in the array, because one element by itself is already sorted we go to the next element. If the second element is smaller than the first one we swap both elements in the array. Next we consider a third element, we swap it leftwards by comparison with the previous elements until the 3rd element is in the correct position. Then we do the same for the next ones.
140+
>Example
141+
Input: An array A of n comparable elements
142+
Output: The array A with elements rearranged in nondecreasing order (ascending order)
143+
144+
for k from 1 to n-1 do
145+
Insert A[k] at its proper location within A[0], A[1],..., A[k]

0 commit comments

Comments
 (0)