2021-08-19 12:20:28

常见排序算法

常见排序算法,快速排序,归并排序,选择排序,冒泡排序代码记录

完整代码

  • 新建文件
  • 复制粘贴
  • 运行代码

效果截图

测试数据

nums := []int{3, 1, 2, 5, 7, 8, 5, 4, 6, 9, 2, 6, 8, 3}

运行结果

image.png

代码

package main

import (
	"log"
)

func main() {
	nums := []int{3, 1, 2, 5, 7, 8, 5, 4, 6, 9, 2, 6, 8, 3}
	log.Println("测试", nums)
	log.Println("归并", mergeSort(nums))
	quicksort(nums, 0, len(nums)-1)
	log.Println("快排", nums)
	nums = []int{3, 1, 2, 5, 7, 8, 5, 4, 6, 9, 2, 6, 8, 3}
	bubberSort(nums)
	log.Println("冒泡", nums)
	nums = []int{3, 1, 2, 5, 7, 8, 5, 4, 6, 9, 2, 6, 8, 3}
	selectSort(nums)
	log.Println("选择", nums)
}

// 快速排序
func quicksort(nums []int, left, right int) {
	if left >= right {
		return
	}
	l, r := left, right
	// 第一个作为分解值
	flag := nums[left]
	for l < r {
		for nums[r] > flag && l < r {
			r--
		}
		// 挪一挪
		for nums[l] <= flag && l < r {
			l++
		}
		nums[l], nums[r] = nums[r], nums[l]
	}
	nums[left], nums[l] = nums[l], nums[left]
	quicksort(nums, left, l-1)
	quicksort(nums, l+1, right)
}

// 归并排序
func mergeSort(nums []int) []int {
	if len(nums) <= 1 {
		return nums
	}
	mid := len(nums) / 2
	left := mergeSort(nums[:mid])
	right := mergeSort(nums[mid:])
	return merge(left, right)
}
func merge(left, right []int) []int {
	ret := make([]int, 0, len(left)+len(right))
	i, j := 0, 0
	for i < len(left) && j < len(right) {
		if left[i] > right[j] {
			ret = append(ret, right[j])
			j++
		} else {
			ret = append(ret, left[i])
			i++
		}
	}
	ret = append(ret, left[i:]...)
	ret = append(ret, right[j:]...)
	return ret
}

// 冒泡排序
func bubberSort(nums []int) {
	for i := 0; i < len(nums)-1; i++ {
		for j := 0; j < len(nums)-1-i; j++ {
			if nums[j] > nums[j+1] {
				nums[j], nums[j+1] = nums[j+1], nums[j]
			}
		}
	}
}

// 选择排序
func selectSort(nums []int) {
	for i := 0; i < len(nums)-1; i++ {
		for j := i; j < len(nums); j++ {
			if nums[i] > nums[j] {
				nums[i], nums[j] = nums[j], nums[i]
			}
		}
	}
}

本文链接:https://blog.zxysilent.com/post/sorts.html

-- EOF --