一、冒泡排序
入门级排序,简单双重循环,以下用go实现
func Sort(a []int) []int {
for i := 0; i < len(a); i++ {
for j := i + 1; j < len(a); j++ {
if a[i] > a[j] {
temp := a[j]
a[j] = a[i]
a[i] = temp
}
}
}
return a
}
二、 插入排序
假设a[0~i]是有序的,那么第i+1 位置的确认,只需要 从i to 0,找到合适的位置即可
// 1,3,2,4,5,7,9,10,22,11
// a[j]
// a[i~ j-1]
// 插入排序
func InsertSort(a []int) []int {
j := 1
for j < len(a) {
cur := a[j]
for i := j - 1; i >= 0; i-- {
if a[i] > cur {
a[i+1] = a[i]
} else {
a[i+1] = cur
break
}
}
j++
}
return a
}
三、 归并排序
func MergeArr(a []int, start, mid, end int, result []int) {
i := start
j := mid + 1
k := 0
for i <= mid && j <= end {
if a[i] <= a[j] {
result[k] = a[i]
i++
} else {
result[k] = a[j]
j++
}
k++
}
for i <= mid {
result[k] = a[i]
i++
k++
}
for j <= end {
result[k] = a[j]
j++
k++
}
for i := 0; i < k; i++ {
a[start+i] = result[i]
}
return
}
func MergeSort(a []int, start, end int, result []int) {
if start < end {
mid := (start + end) / 2
MergeSort(a, start, mid, result)
MergeSort(a, mid+1, end, result)
MergeArr(a, start, mid, end, result)
}
return
}
四、堆排序
完全二叉树的性质
1、维护大顶堆,根节点大于左右
2、用数组存在时,i 为根节点,左右节点分别为2i+1 2i+2
维护大顶堆代码
func maxHeapify(a []int,heapSize,i int) {
if i >= heapifySize {
return
}
left := 2*i + 1
right := 2*i + 2
max := i
if left <= heapSize && a[left] > a[max] {
max = left
}
if right <= heapSize && a[right] > a[max] {
max = right
}
if max != i {
swap(a,i,max)
maxHeapify(a,heapSize,max)
}
}
建堆
func bulidMaxHeapify(a []int) {
heapifySize := len(a) - 1
i := len(a)/2
for i >= 0 {
maxHeapify(a,heapifySize,i)
i--
}
}
堆排序
func heapSort(a []int) {
// 建堆
bulidMaxHeapify(a)
length := len(a) - 1
for ;i>=0;i-- {
swap(a,i,0)
length -= 1
maxHeapify(a, length, 0)
}
}
五、快速排序
func quickSort(a []int, p, r int) {
if p < r {
q := partition(a, p, r)
quickSort(a, p, q-1)
quickSort(a, q+1, r)
}
}
func partition(a []int, p, r int) int {
x := a[r]
i := p - 1
for j := p; j <= r-1; j++ {
if a[j] <= x {
i += 1
swap(a, i, j)
}
}
swap(a, i+1, r)
return i + 1
}