Skip to content

Commit d493582

Browse files
authored
Update sorting_algorithms.py
Added temp merge sort
1 parent 44e905a commit d493582

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

HackerEarth/sorting_algorithms.py

+51
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,54 @@
116116
answer[count] = numlist.index(originalnumlist[count]) + 1
117117

118118
print(' '.join(list(map(str,answer))))
119+
120+
121+
"""
122+
Merge Sort
123+
124+
Time Complexity:
125+
The list of size N is divided into a max of log N parts, and the merging of all sublists into a single list takes O(N) time, the worst
126+
case run time of this algorithm is O(N Log N)
127+
128+
Given an array A on size N, you need to find the number of ordered pairs (i, j) such that i < j and A[i] > A[j].
129+
Input:
130+
First line contains one integer, N, size of array.
131+
Second line contains N space separated integers denoting the elements of the array A.
132+
Output:
133+
Print the number of ordered pairs (i, j) such that i < j and A[i] > A[j].
134+
Constraints:
135+
1 \le N \le 10^6
136+
1 \le A[i] \le 10^6
137+
"""
138+
139+
#Merge Sort (Recursive)
140+
def merge(left,right):
141+
#print("[DEBUG:merge] Merging " + str(left) + " and " + str(right))
142+
result = []
143+
for l_item in left:
144+
if (right != []):
145+
while (l_item > right[0]):
146+
result.append(right.pop(0))
147+
if right == []:
148+
break
149+
result.append(l_item)
150+
if right != []:
151+
for item in right:
152+
result.append(item)
153+
return result
154+
155+
def mergesort(nlist,end): #start = 0
156+
mid = int(end/2)
157+
if end == 0:
158+
return nlist
159+
else:
160+
return merge(mergesort(nlist[:mid+1],mid),mergesort(nlist[mid+1:],end-(mid+1)))
161+
162+
size = int(input())
163+
numlist = list(map(int,input().split()))
164+
answer = mergesort(numlist,size-1)
165+
print(answer)
166+
167+
#Merge Sort
168+
169+

0 commit comments

Comments
 (0)