https://github.com/simonwei97/gitbook-algo
https://github.com/simonwei97/gitbook-algo
Last synced: 4 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/simonwei97/gitbook-algo
- Owner: simonwei97
- Created: 2023-12-03T15:01:51.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-12-03T15:41:47.000Z (over 2 years ago)
- Last Synced: 2025-02-24T15:51:11.897Z (over 1 year ago)
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
---
description: 常考排序
---
# 排序算法
### 快速排序
```go
func QuickSort(nums []int) []int {
// 思路:把一个数组分为左右两段,左段小于右段
quickSort(nums, 0, len(nums)-1)
return nums
}
// 原地交换,所以传入交换索引
func quickSort(nums []int, start, end int) {
if start < end {
// 分治法:divide
pivot := partition(nums, start, end)
quickSort(nums, 0, pivot-1)
quickSort(nums, pivot+1, end)
}
}
// 分区
func partition(nums []int, start, end int) int {
// 选取最后一个元素作为基准pivot
p := nums[end]
i := start
// 最后一个值就是基准所以不用比较
for j := start; j < end; j++ {
if nums[j] < p {
swap(nums, i, j)
i++
}
}
// 把基准值换到中间
swap(nums, i, end)
return i
}
// 交换两个元素
func swap(nums []int, i, j int) {
t := nums[i]
nums[i] = nums[j]
nums[j] = t
}
```