Golang中数组反转的实现方式

The array or slice reverse in golang

Posted by alovn on January 19, 2020

Golang中数组反转的实现方式

直接上代码了~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package array

import (
    "reflect"
    "sort"
)
// 方式一
func ReverseSlice(s interface{}) {
    size := reflect.ValueOf(s).Len()
    swap := reflect.Swapper(s)
    for i, j := 0, size-1; i < j; i, j = i+1, j-1 {
        swap(i, j)
    }
}

// 方式二: SliceStable
func Reverse(s interface{})  {
    sort.SliceStable(s, func(i, j int) bool {
        return true
    })
}

// 方式三:
nums := []int{4, 3, 5, 6, 1, 4, 5}
sort.Stable(sort.Reverse(sort.IntSlice(nums)))

SliceStable是在Go的sort包中一个很强大的Slice排序函数,它是将排序函数作为参数的:

1
func SliceStable(slice interface{}, less func(i, j int) bool)

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func main() {
    example := []int{4,3,2,1,5,9,8,7,6}
    array.ReverseSlice(example)
    fmt.Println("example after reversed: ", example)

    example1 := []int{1, 25, 3, 5, 4}
    array.Reverse(example1)
    fmt.Println("example1 after reversed: ", example1)

    example2 := []string{"a", "c", "b"}
    array.Reverse(example2)
    fmt.Println("example2 after reversed: ", example2)
}

// Output:
// example after reversed:  [6 7 8 9 5 1 2 3 4]
// example1 after reversed:  [4 5 3 25 1]
// example2 after reversed:  [b c a]

golang中有一段比较好玩的用于反转的代码:

1
2
3
4
5
6
7
8
9
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
  a[i], a[j] = a[j], a[i]
}
/*
a的定义需要为:
a := []int{3, 1, 2}
或
a := []interface{}{"a", "c", "b"}
*/