Skip to content

Files

Latest commit

 

History

History
73 lines (61 loc) · 1.62 KB

0075. Sort Colors.md

File metadata and controls

73 lines (61 loc) · 1.62 KB
Screen Shot 2023-05-27 at 2 02 06 AM

Bubble Sort

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */

var sortColors = function(nums) {
    for(let i = 0; i < nums.length; i++) {
        for(let j = i + 1; j < nums.length; j++) {
            if(nums[i] > nums[j]) {
                [nums[i], nums[j]] = [nums[j], nums[i]]
            }
        }
    }
};

Selection Sort

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
    for(let i = 0; i < nums.length; i++) {
        let ptr = i;
        for(let j = i + 1; j < nums.length; j++) {
            if(nums[ptr] > nums[j]) {
                ptr = j;
            }
        }
        [nums[i], nums[ptr]] = [nums[ptr], nums[i]];
    }
    return nums;
};

One Pass -> Dutch National Flag Problem

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
    let left = 0;
    let right = nums.length - 1;
    let current = left;
    
    const swap = (i, j) => [nums[i], nums[j]] = [nums[j], nums[i]]
    
    while(current <= right) {
        if(nums[current] === 0) {
            swap(left, current);
            left++;
            current++;
        } else if(nums[current] === 2) {
            swap(right, current);
            right--;
        } else {
            current++;
        }
    }
};