Skip to content

Commit 702da49

Browse files
author
komal.bansal1
committed
sort01 added using partition method of quick sort
1 parent 01d8213 commit 702da49

File tree

2 files changed

+56
-18
lines changed

2 files changed

+56
-18
lines changed

Array/sort_0_1.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
https://www.geeksforgeeks.org/problems/segregate-0s-and-1s5106/1
3+
Given an array of length n consisting of only 0's and 1's in random order. Modify the array in-place to segregate 0s on the left side and 1s on the right side of the array.
4+
5+
Example 1:
6+
Input:
7+
n = 5
8+
arr[] = {0, 0, 1, 1, 0}
9+
Output: {0, 0, 0, 1, 1}
10+
Explanation:
11+
After segregate all 0's on the left and 1's on the right modify array will be {0, 0, 0, 1, 1}.
12+
13+
Example 2:
14+
Input:
15+
n = 4
16+
arr[] = {1, 1, 1, 1}
17+
Output: {1, 1, 1, 1}
18+
Explanation: There are no 0 in the given array, so the modified array is 1 1 1 1.
19+
'''
20+
21+
# use partition method of quick sort to move 0 on left and 1 on right side
22+
class Solution:
23+
def segregate0and1(self, arr, n):
24+
25+
pivot = 0
26+
i = 0
27+
j = 0
28+
29+
while j < n:
30+
if arr[j] == pivot:
31+
arr[i], arr[j] = arr[j], arr[i]
32+
i += 1
33+
j += 1
34+
else:
35+
j += 1

Array/sort_0_1_2.py

+21-18
Original file line numberDiff line numberDiff line change
@@ -22,22 +22,25 @@
2222
# if mid = 0, swap with low then low += 1 & mid += 1
2323
# if mid = 1, mid += 1
2424
# else swap mid with high, high -= 1
25+
# similar to sort_0_1, following partitioning method
26+
# i = 0 region, j = 1 region, k = 2 region
2527
class Solution:
26-
def sortColors(self, arr: List[int]):
27-
28-
n = len(arr)
29-
low = 0
30-
high = n-1
31-
mid = 0
32-
33-
while mid <= high:
34-
35-
if arr[mid] == 0:
36-
arr[mid], arr[low] = arr[low], arr[mid]
37-
low += 1
38-
mid += 1
39-
elif arr[mid] == 1:
40-
mid += 1
41-
else:
42-
arr[mid], arr[high] = arr[high], arr[mid]
43-
high -= 1
28+
def sortColors(self, nums: List[int]) -> None:
29+
"""
30+
Do not return anything, modify nums in-place instead.
31+
"""
32+
i = 0
33+
j = 0
34+
k = len(nums)-1
35+
36+
while j <= k:
37+
if nums[j] == 1: # if j is in correct region
38+
j += 1
39+
elif nums[j] == 0: # if j found 0, means move to i region
40+
nums[i], nums[j] = nums[j], nums[i]
41+
i += 1
42+
j += 1
43+
else: # if j found 2, means move to k region
44+
nums[k], nums[j] = nums[j], nums[k]
45+
k -= 1
46+

0 commit comments

Comments
 (0)