github.com/niubaoshu/goutils@v0.0.0-20180828035119-e8e576f66c2b/quicksort.go (about)

     1  package goutils
     2  
     3  func qsort(a []int) []int {
     4  	if len(a) < 2 {
     5  		return a
     6  	}
     7  
     8  	left, right := 0, len(a)-1
     9  
    10  	//Pick a pivot
    11  	//pivotIndex := 0
    12  	//
    13  	//Move the pivot to the right
    14  	//a[pivotIndex], a[right] = a[right], a[pivotIndex]
    15  
    16  	// Pile elements smaller than the pivot on the left
    17  	for i := range a {
    18  		if a[i] < a[right] {
    19  			a[i], a[left] = a[left], a[i]
    20  			left++
    21  		}
    22  	}
    23  
    24  	// Place the pivot after the last smaller element
    25  	a[left], a[right] = a[right], a[left]
    26  
    27  	// Go down the rabbit hole
    28  	qsort(a[:left])
    29  	qsort(a[left+1:])
    30  
    31  	return a
    32  }