
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Colors in Python
Suppose we have an array with n objects. These are colored red, white, or blue, sort them in place so that the objects of the same color are adjacent. So with the colors in the order red, white and blue. Here, we will use the numbers like 0, 1, and 2 to represent the color red, white, and blue respectively. So if the array is like [2,0,2,1,1,0], then the output will be [0,0,1,1,2,2]
To solve this, we will follow these steps −
- set low := 0, mid := 0 and high := length of array – 1
- while mid <= high
- if arr[mid] = 0, then swap arr[mid] and arr[low], and increase low and mid by 1
- otherwise when arr[mid] = 2, swap arr[high] and arr[mid], decrease high by 1
- else increase mid by 1
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def sortColors(self, nums): low = 0 mid = 0 high = len(nums)-1 while mid<=high: if nums[mid] == 0: nums[low],nums[mid] = nums[mid],nums[low] low+=1 mid += 1 elif nums[mid] == 2: nums[high], nums[mid] = nums[mid], nums[high] high-=1 else: mid += 1 return nums ob1 = Solution() print(ob1.sortColors([2,0,2,1,1,0]))
Input
[2,0,2,1,1,0]
Output
[0,0,1,1,2,2]
Advertisements