八大排序算法

快速排序

package main

import "fmt"

func quickSort(a []int, left, right int) {

	if right <= left {
		return
	}
	temp := a[left] //选取第一个数为哨兵。
	i, j := left, right
	for i < j {
		for a[j] >= temp && j > i {
			j--
		}
		for a[i] <= temp && i < j {
			i++
		}
		if j > i {
			t := a[i]
			a[i] = a[j]
			a[j] = t
		}
		//fmt.Print(a)
	}
	a[left] = a[i]
	a[i] = temp
	quickSort(a, left, i-1)
	quickSort(a, i+1, right)

}

func main() {
	a := []int{9, 45, 23, 45, 23, 34, 34, 2, 21, 5, 3, 2, 9, -5, 0, 3}
	//a := []int{6, 5, 3, 2, 9, 5, 6, 3}
	len := len(a)
	quickSort(a, 0, len-1)
	fmt.Print(a)
}

冒泡排序

package main

import "fmt"

func bubbleSort(a []int) {
	len := len(a)
	for i := 0; i < len; i++ {
		for j := i + 1; j < len; j++ {
			// 升序排列
			if a[j] < a[i] {
				a[j], a[i] = a[i], a[j]
			}
		}

	}
}

func main() {
	a := []int{9, 45, 23, 45, 23, 34, 34, 2, 21, 5, 3, 2, 9, -5, 0, 3}
	//a := []int{6, 5, 3, 2, 9, 5, 6, 3}

	bubbleSort(a)
	fmt.Print(a)
}