Sort Colors II – Python 3 (Week 18 – 09)

class Solution:
    """
    @param colors: A list of integer
    @param k: An integer
    @return: nothing
    """
    def sortColors2(self, colors, k):
        # write your code here
        self.quickSort(colors, 1, k, 0, len(colors) - 1)
        
        
    def quickSort(self, colors, color_from, color_end, index_from, index_end):
        if color_from == color_end or index_from == index_end:
            return
        
        color = (color_from + color_end) // 2
        
        left, right = index_from, index_end
        
        while left <= right:
            while left <= right and colors[left] <= color:
                left += 1
            while left <= right and colors[right] > color:
                right -= 1
            if left <= right:
                colors[left], colors[right] = colors[right], colors[left]
                left += 1
                right -= 1
                
        self.quickSort(colors,color_from, color, index_from, right)
        self.quickSort(colors,color + 1, color_end, left, index_end)

Leave a comment

Design a site like this with WordPress.com
Get started