逆序对的数量-golang
逆序对的数量-golang
package main
import "fmt"
var n int
var arr []int
func main(){
fmt.Scanf("%d", &n)
arr = make([]int, n)
for i := 0; i <n; i++{
fmt.Scanf("%d", &arr[i])
}
var num int
mergeSort(arr, 0, n-1, &num)
fmt.Println(num)
}
func mergeSort(arr []int, l, r int, num *int){
if l >= r{
return
}
mid := (l+r)>>1
mergeSort(arr, l, mid, num)
mergeSort(arr, mid+1, r, num)
tmp := make([]int, 0, r-l+1)
i, j := l, mid+1
for i <= mid && j <= r{
if arr[i] <= arr[j]{
tmp = append(tmp, arr[i])
i++
continue
}
tmp = append(tmp, arr[j])
*num+= mid-i+1
j++
}
for i <= mid{
tmp = append(tmp, arr[i])
i++
}
for j <= r{
tmp = append(tmp, arr[j])
j++
}
copy(arr[l:r+1], tmp)
}