Skip to content

Commit ccbf8a7

Browse files
authored
Create SortedSquaredArray2.py
1 parent dec6f96 commit ccbf8a7

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others.
2+
# E-Mail : info@careermonk.com
3+
# Creation Date : 2014-01-10 06:15:46
4+
# Last modification : 2008-10-31
5+
# by : Narasimha Karumanchi
6+
# Book Title : Data Structures And Algorithmic Thinking With Python
7+
# Warranty : This software is provided "as is" without any
8+
# warranty; without even the implied warranty of
9+
# merchantability or fitness for a particular purpose.
10+
11+
def sortedSquaredArray(A):
12+
n = len(A)
13+
j = 0
14+
# Find the last index of the negative numbers
15+
while j <n and A[j] < 0:
16+
j += 1
17+
# i points to the last index of negative numbers
18+
i = j-1
19+
result = []
20+
# j points to the first index of the positive numbers
21+
while i >= 0 and j < n:
22+
if A[i]**2 < A[j]**2:
23+
result.append(A[i]**2)
24+
i -= 1
25+
else:
26+
result.append(A[j]**2)
27+
j += 1
28+
29+
# add the remaining negative numbers squares to result
30+
while i>= 0:
31+
result.append(A[i]**2)
32+
i -= 1
33+
34+
# add the remaining positive numbers squares to result
35+
while j < n:
36+
result.append(A[j]**2)
37+
j += 1
38+
39+
return result

0 commit comments

Comments
 (0)