Skip to content

Commit 44e905a

Browse files
authored
Update sorting_algorithms.py
Add Insertion Sort
1 parent 8d33da4 commit 44e905a

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

HackerEarth/sorting_algorithms.py

+45-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""
22
Bubble Sort
33
Complexity:
4-
The complexity of bubble sort is O(n**2) in both worst and average cases, because the entire array needs to be iterated for every element.
4+
The complexity of bubble sort is O(n**2) in both worst and average cases, because the entire array needs to be iterated for every
5+
element.
56
67
You have been given an array A of size N . you need to sort this array non-decreasing oder using bubble sort. However, you do not
78
need to print the sorted array . You just need to print the number of swaps required to sort this array using bubble sort
@@ -72,3 +73,46 @@
7273
print(' '.join(list(map(str,numlist))))
7374

7475

76+
"""
77+
Insertion Sort
78+
79+
Time Complexity:
80+
In worst case,each element is compared with all the other elements in the sorted array. For N elements, there will be N^2 comparisons.
81+
Therefore, the time complexity is O(N^2)
82+
83+
You have been given an A array consisting of N integers. All the elements in this array are guaranteed to be unique. For each position
84+
i in the array A you need to find the position A[i] should be present in, if the array was a sorted array. You need to find this for
85+
each i and print the resulting solution.
86+
Input Format:
87+
The first line contains a single integer N denoting the size of array A. The next line contains N space separated integers denoting
88+
the elements of array A.
89+
Output Format:
90+
Print N space separated integers on a single line , where the Ith integer denotes the position of A[i] if this array were sorted.
91+
Constraints:
92+
1 \le N \le 100
93+
1 \le A[i] \le 100
94+
"""
95+
96+
size = int(input())
97+
originalnumlist = list(map(int,input().split()))
98+
numlist = []
99+
answer = []
100+
for item in originalnumlist:
101+
numlist += [item] # create a copy
102+
answer += [item] # create a copy
103+
temp = 0
104+
105+
# --- Begin Insertion Sort Logic --- #
106+
for x in range(0,size):
107+
temp = numlist[x]
108+
place = x
109+
while (place > 0) and (numlist[place-1] > temp):
110+
numlist[place] = numlist[place-1]
111+
place -= 1
112+
numlist[place] = temp
113+
# --- End Insertion Sort Logic --- #
114+
115+
for count in range(0,size):
116+
answer[count] = numlist.index(originalnumlist[count]) + 1
117+
118+
print(' '.join(list(map(str,answer))))

0 commit comments

Comments
 (0)