Skip to content

Commit d402401

Browse files
committed
Sort an Array
1 parent 471e0d5 commit d402401

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Sort_an_Array.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Given an array of integers nums, sort the array in ascending order.
2+
#
3+
# Example 1:
4+
#
5+
# Input: nums = [5,2,3,1]
6+
# Output: [1,2,3,5]
7+
# Example 2:
8+
#
9+
# Input: nums = [5,1,1,2,0,0]
10+
# Output: [0,0,1,1,2,5]
11+
12+
13+
def sortArray(nums):
14+
def helper(nums, start, end):
15+
16+
if start >= end:
17+
return
18+
19+
pivot = start
20+
left = start + 1
21+
right = end
22+
23+
while left <= right:
24+
25+
if nums[left] > nums[pivot] and nums[right] < nums[pivot]:
26+
nums[left], nums[right] = nums[right], nums[left]
27+
28+
if nums[left] < nums[pivot]:
29+
left += 1
30+
31+
if nums[right] > nums[pivot]:
32+
right -= 1
33+
34+
nums[pivot], nums[right] = nums[right], nums[pivot]
35+
36+
leftSubArrayisSmaller = right - 1 - start < end - (right + 1)
37+
38+
if leftSubArrayisSmaller:
39+
helper(nums, start, right - 1)
40+
helper(nums, right + 1, end)
41+
else:
42+
helper(nums, right + 1, end)
43+
helper(nums, start, right - 1)
44+
45+
helper(nums, 0, len(nums) - 1)
46+
return nums

0 commit comments

Comments
 (0)