Skip to content

Commit 89ba06c

Browse files
feat(abs-sort): add absolute value sort for array
1 parent 8ee802a commit 89ba06c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

abs-sort/abs-sort.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# A = [-3, -1, 3, 5, 7]
2+
# B = [1, 3, 3, 5, 7]
3+
4+
# A = [-6, -4, -1, 3, 5, 7]
5+
# result = [1, 3, 4, 5, 6, 7]
6+
7+
8+
def abs_sort(array):
9+
if not array:
10+
return []
11+
12+
left_idx = 0
13+
right_idx = len(array) - 1
14+
15+
result = [0] * len(array)
16+
resultIdx = len(result) - 1
17+
18+
while left_idx <= right_idx:
19+
if abs(array[left_idx]) > abs(array[right_idx]):
20+
result[resultIdx] = abs(array[left_idx])
21+
left_idx += 1
22+
else:
23+
result[resultIdx] = abs(array[right_idx])
24+
right_idx -= 1
25+
26+
resultIdx -= 1
27+
28+
return result
29+
30+
31+
print(abs_sort([-3, -1, 3, 5, 7]))
32+
print(abs_sort([-6, -4, -1, 3, 5, 7]))
33+
print(abs_sort([-6, -4, -3, -1]))
34+
print(abs_sort([3, 4, 9, 10]))

0 commit comments

Comments
 (0)