关于go:go实现归并排序

46次阅读

共计 655 个字符,预计需要花费 2 分钟才能阅读完成。

package mergeSort

func mergeSort(nums []int) []int {if len(nums) < 2 {return nums}
    m := len(nums) / 2
    l := mergeSort(nums[:m])
    r := mergeSort(nums[m:])
    return merge(l, r)
}

func merge(left, right []int) []int {
    i, j := 0, 0
    n, m := len(left), len(right)
    reslet := make([]int, n+m)
    for i < n && j < m {if left[i] <= right[j] {reslet[i+j] = left[i]
            i++
        } else {reslet[i+j] = right[j]
            j++
        }
    }
    for i < n {reslet[i+j] = left[i]
        i++
    }
    for j < m {reslet[i+j] = right[j]
        j++
    }
    return reslet
}
package mergeSort

import (
    "math/rand"
    "testing"
    "time"
)

func TestMergeSort(t *testing.T) {var input [100]int
    r := rand.New(rand.NewSource(time.Now().Unix()))
    // 初始化数组 input[]
    for i := 0; i < 100; i++ {input[i] = r.Intn(1000)
    }
    output := mergeSort(input[:])
    for i := 0; i <= 10; i++ {println(output[i])
    }
}

正文完
 0