This is a creation in Article, where the information may have evolved or changed.
Problem description
The. Sort Colors
Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Bubble sort
Algorithm description
1 traversing the sequence to be sorted
2 Compare adjacent two numbers, unequal swap positions put large numbers behind decimals
3 Repeat the above steps until the sorted sequence is empty, or no interchange occurs, indicating that sorting is complete
Code implementation
/** * 最差时间复杂度 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 } }}
Select sort
Algorithm description
1 initially finds the smallest element in the sequence and places it at the beginning of the sequence as a sorted sequence
2 continue to find the smallest element from the remaining unsorted elements, and place it at the end of the sorted sequence
3 Repeat the above steps until all elements are sorted
Code implementation
/** * 最差时间复杂度 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 } } }
Insert Sort
Algorithm description
1 starting with the first element, the element can be thought of as having an orderly
2 Take out the next element and traverse from the back forward in the ordered sequence
3 If the ordered column is greater than the new element, move the ordered element to the next position
4 Repeat step 3 until you find the position where the row element is less than or equal to the new element
5 after inserting a new element into the location, repeat steps 2~5
Code implementation
/** * Worst time complexity O (n^2) * Optimal time complexity O (n) * Average time complexity O (n^2) * Required auxiliary space O (1) * Stable stability **/func sortcolors (nums []int) {if Len (nums) <= 0 {return} temp: = 0 for I: = 1; i < Len (nums); i++ {tem p = nums[i] J: = I-1 for; J >= 0 && nums[j] > temp; {nums[j+1] = nums[j] j--} nums[j+1] = temp}}