75. Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.算法
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.code
1 遍历待排序序列
2 比较相邻两个数,不相等则交换位置把大数放在小数后面
3 重复以上步骤,直到待排序序列为空,或无交换发生,说明排序完成排序
/** * 最差时间复杂度 O(n^2) * 最优时间复杂度 O(n) * 平均时间复杂度 O(n^2) * 所需辅助空间 O(1) * 稳定性 稳定 **/ func sortColors(nums []int) { length := len(nums) if length <= 1 { return } swapFlag := false temp := 0 for i := 0; i < length; i++ { swapFlag = false for j := 0; j < length-i-1; j++ { if nums[j] > nums[j+1] { temp = nums[j] nums[j] = nums[j+1] nums[j+1] = temp swapFlag = true } } if !swapFlag { // 说明已经排好序 break } } }
1 初始时在序列中找到最小元素,放到序列的起始位置做为已排序序列
2 再从剩余未排序元素中继续寻找最小元素,放到已排序序列的末尾
3 重复以上步骤,直到全部元素均排序完毕ip
/** * 最差时间复杂度 O(n^2) * 最优时间复杂度 O(n^2) * 平均时间复杂度 O(n^2) * 所需辅助空间 O(1) * 稳定性 不稳定 **/ func sortColors(nums []int) { if len(nums) <= 0 { return } temp, index := 0, 0 for i := 0; i < len(nums); i++ { // 已排序列 index = i for j := i + 1; j < len(nums); j++ { // 未排序列 if nums[j] < nums[index] { index = j temp = nums[i] } } if index != i { nums[i] = nums[index] nums[index] = temp } } }
1 从第一个元素开始,该元素能够认为已排好序
2 取出下一个元素,在已排序列中从后向前遍历
3 若已排序列大于新元素,将已排元素移到下一位置
4 重复步骤3,直到找到已排元素小于或者等于新元素的位置
5 将新元素插入到该位置后,重复步骤2~5leetcode
/** * 最差时间复杂度 O(n^2) * 最优时间复杂度 O(n) * 平均时间复杂度 O(n^2) * 所需辅助空间 O(1) * 稳定性 稳定 **/ func sortColors(nums []int) { if len(nums) <= 0 { return } temp := 0 for i := 1; i < len(nums); i++ { temp = nums[i] j := i - 1 for ; j >= 0 && nums[j] > temp; { nums[j+1] = nums[j] j-- } nums[j+1] = temp } }