Three-direction Segmentation quick Sort (Golang implementation)

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Encapsulated into functions:

//三向切分快速排序func ThreeWayQuickSort(s []int) {    sort3way(s, 0, len(s)-1)} //在lt之前的(lo~lt-1)都小于中间值//在gt之前的(gt+1~hi)都大于中间值//在lt~i-1的都等于中间值//在i~gt的都还不确定(最终i会大于gt,即不确定的将不复存在)func sort3way(s []int, lo, hi int) {    if lo >= hi {        return    }    v, lt, i, gt := s[lo], lo, lo+1, hi    for i <= gt {        if s[i] < v {            swap(s, i, lt)            lt++            i++        } else if s[i] > v {            swap(s, i, gt)            gt--        } else {            i++        }    }    sort3way(s, lo, lt-1)    sort3way(s, gt+1, hi)} func swap(s []int, i int, j int) {    s[i], s[j] = s[j], s[i]}

Test:

s := []int{9, 0, 6, 5, 8, 2, 1, 7, 4, 3}fmt.Println(s)ThreeWayQuickSort(s)fmt.Println(s)

Output:
[9 0 6 5 8 2 1 7 4 3]
[0 1 2 3 4 5 6 7 8 9]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.