Skip to content

Instantly share code, notes, and snippets.

View luoheng23's full-sized avatar

luoheng luoheng23

View GitHub Profile
func merge(A []int, p, q, r int) {
const INTMAX = int(^uint(0) >> 1)
A1, A2 := make([]int, q-p), make([]int, r-q)
copy(A1, A[p:q])
copy(A2, A[q:r])
A1, A2 = append(A1, INTMAX), append(A2, INTMAX)
i, j, k := 0, 0, 0
for k = p; k < r; k++ {
if A1[i] >= A2[j] {
A[k] = A2[j]
@luoheng23
luoheng23 / inversion.go
Last active July 29, 2019 09:08
查找数组中逆序对数目,利用归并排序,时间复杂度为O(nlgn)
func count(A []int, p, q, r int) int {
const INTMAX = int(^uint(0) >> 1)
A1, A2 := make([]int, q-p), make([]int, r-q)
copy(A1, A[p:q])
copy(A2, A[q:r])
A1, A2 = append(A1, INTMAX), append(A2, INTMAX)
i, j, k := 0, 0, 0
count := 0
n1 := len(A1) - 1
for k = p; k < r; k++ {
@luoheng23
luoheng23 / quick_sort.go
Created July 31, 2019 02:03
1. 快速排序 2. 随机划分的快速排序 3. Go协程快速排序 4. 相同元素的快速排序 5. 尾递归的快速排序
func partition(A []int, p, r int) int {
x, i := A[r-1], p
for j := p; j < r-1; j++ {
if A[j] <= x {
A[i], A[j] = A[j], A[i]
i++
}
}
A[i], A[r-1] = A[r-1], A[i]
return i
@luoheng23
luoheng23 / cmd.cmd
Created August 1, 2019 11:51
使用python自带的cProfile,分析各个函数的调用和性能情况
python -m cProfile target.py
// Quack.c: an array-based implementation of a quack
#include <stdio.h>
#include <stdlib.h>
typedef struct node *Quack;
Quack createQuack(void); // create and return Quack
Quack destroyQuack(Quack); // remove the Quack
void push(int, Quack); // put int on the top of the quack
void qush(int, Quack); // put int at the bottom of the quack
// InsertionSortForBucketSort O(n^2)
func InsertionSortForBucketSort(A []float64) {
for j := 1; j < len(A); j++ {
key, i := A[j], j-1
for i >= 0 && A[i] > key {
A[i+1] = A[i]
i--
}
A[i+1] = key
}
// CountSort O(n + k)
func CountSort(A []int, k int) {
c := make([]int, k+1)
for _, a := range A {
c[a]++
}
for i := 1; i < k+1; i++ {
c[i] += c[i-1]
}
// CountSortForRadixSort O(n)
func CountSortForRadixSort(A []int, d int, k int) {
dNum := 1
for i := 0; i < d; i++ {
dNum *= k
}
c := make([]int, 11)
for _, a := range A {
c[a/dNum%k]++
}
func Min(A []int) int {
if len(A) < 1 {
return 0
}
min := A[0]
for _, a := range A {
if a < min {
min = a
}
}