Golang basic composite type - basic sorting algorithm (bubble, selection)

1. Bubble sorting

1. Sorting ideas

 2.Code demonstration

Function: Give an integer slice arranged from large to small, and output the slices arranged from small to large.

package main

import "fmt"

func main()  {
	num := []int{9,8,7,6,5,4,3,2,1}
	fmt.Println(BubbleSort(num))
}
func BubbleSort(num []int) []int {
	var temp int
	for i:=0;i<len(num)-1;i++{
		for j:=0;j<len(num)-1-i;j++{
			if num[j]>num[j+1] {
				temp = num[j]
				num[j] = num[j+1]
				num[j+1] = temp
			}
		}
	}
	return num
}

result:

 2. Select sorting

1. Sorting ideas

The first pass of sorting selects the record with the smallest value among all n records to be sorted, and exchanges its position with the first record in the data table, so that the record with the smallest value is at the front of the data table; the second pass sorts the record with the smallest value among the remaining n records. Select the record with the smallest value from the n-1 records below, and exchange it with the second record in the data table, so that the record with the next smallest value is in the second position of the data table; repeat this operation once Select the elements with the third smallest and fourth smallest values ​​in the data table, and replace them with the third and fourth... positions in the data table respectively. A total of n-1 sorting operations are performed, and finally the data table can be arranged in ascending order. The idea of ​​​​arranging in descending order is the same, replacing the positions with larger values.

2.Code demonstration

  •  first pass code
package main

import "fmt"

func main()  {//考虑第一趟的情况
	//1.找出切片中最小的数
	//2.和切片中第一个数进行位置交换
	s:=[]int{38,0,46,38,74,91,12,25}
	min := s[0]//存储最小值 ,默认第一个
	minindex := 0 //存储最小值下标,默认第一个
	for i:= 0+1;i<len(s);i++{
		if min > s[i]{
			min = s[i]
			minindex = i
		}
	}
	if minindex!=0{
		s[0],s[minindex] = s[minindex],s[0]
	}
	fmt.Println(s)

}

Output:

[0 38 46 38 74 91 12 25]

  • Complete code
package main

import "fmt"

func main()  {
	s:=[]int{38,0,46,38,74,91,12,25}
	for j:= 0;j<len(s)-1;j++{
		min := s[j]//存储最小值 ,默认第一个
		minindex := j //存储最小值下标,默认第一个
		for i:= j+1;i<len(s);i++{
			if min > s[i]{
				min = s[i]
				minindex = i
			}
		}
		if minindex!=j{
			s[j],s[minindex] = s[minindex],s[j]
		}
		fmt.Println(s)
	}


}

Output result:

[0 38 46 38 74 91 12 25]
[0 12 46 38 74 91 38 25]
[0 12 25 38 74 91 38 46]
[0 12 25 38 74 91 38 46]
[0 12 25 38 38 91 74 46]
[0 12 25 38 38 46 74 91]
[0 12 25 38 38 46 74 91]

 

Guess you like

Origin blog.csdn.net/weixin_41551445/article/details/126297371