-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquared_array_sort2.py
More file actions
54 lines (42 loc) · 828 Bytes
/
squared_array_sort2.py
File metadata and controls
54 lines (42 loc) · 828 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
array = [0,2,9,8,-6,-7,4,-3,2]
def merge_sort(array):
if len(array) <= 1:
return array
mid = len(array) // 2
left = merge_sort(array[:mid])
right = merge_sort(array[mid:])
return merge(left,right)
def merge(left,right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
arr = merge_sort(array)
n = len(arr)
result = [0]*n
left = 0
right = n - 1
position = n -1
while left <= right:
if arr[left]**2 > arr[right]**2:
result[position] = arr[left]**2
left += 1
else:
result[position] = arr[right]**2
right -= 1
position -= 1
arr = result
print(arr)