Skip to content

Commit 0128317

Browse files
authored
Insertion Sort
1 parent 9b6cc8f commit 0128317

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Insertion Sort

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
# Programmer : Dhruv Patel
3+
# Problem Name : Insertion Sort
4+
# Used In : Python
5+
# Used As : Practice
6+
# Problem =>
7+
# Implementation of Insertion - sort
8+
# Thoughts =>
9+
# Insertion sort works the way we sort the cards in the hand.
10+
# We start with empty left hand and the cards face down on the
11+
# table. We then remove one card at a time from the table and insert
12+
# it into the correct postion in the left hand.To find the correct
13+
# position for a card, we compare it with each of the card already in
14+
# the hand, from right to left.At all times, the cards held in the left
15+
# hand are sorted, and these cards were originally the top cards of the
16+
# pile on the table.
17+
# The algorithms sort the numbers in place so the space - Complexity will
18+
# be O(1) just like the bubble sort.
19+
# Time - Complexity =>
20+
Best - Ω(n)
21+
Average - Θ(n^2)
22+
Worst - O(n^2)
23+
24+
# Space - Complexity =>
25+
Worst - Θ(1)
26+
"""
27+
import random
28+
import time
29+
def insertion_sort(x):
30+
l = []
31+
for j in range(x):
32+
l.append(random.randint(-9999, 9999))
33+
N = len(l)
34+
start_time = time.time()
35+
for j in range(1,N):
36+
key = l[j]
37+
i = j - 1
38+
while i >= 0 and l[i] > key:
39+
l[i+1] = l[i]
40+
i = i - 1
41+
l[i+1] = key
42+
return time.time() - start_time
43+
44+
print("The round-time elapsed to sort 1000 elements by insertion sort ", round(insertion_sort(1000)))
45+
print("The round-time elapsed to sort 2000 elements by insertion sort ", round(insertion_sort(2000)))
46+
print("The round-time elapsed to sort 3000 elements by insertion sort ", round(insertion_sort(4000)))
47+
print("The round-time elapsed to sort 4000 elements by insertion sort ", round(insertion_sort(8000)))
48+
print("The round-time elapsed to sort 5000 elements by insertion sort ", round(insertion_sort(16000)))
49+
50+
'''
51+
Output :-
52+
The round-time elapsed to sort 1000 elements by insertion sort 0
53+
The round-time elapsed to sort 2000 elements by insertion sort 1
54+
The round-time elapsed to sort 3000 elements by insertion sort 2
55+
The round-time elapsed to sort 4000 elements by insertion sort 9
56+
The round-time elapsed to sort 5000 elements by insertion sort 38
57+
'''
58+
59+
60+
61+
62+
63+

0 commit comments

Comments
 (0)