github.com/andy2046/gopie@v0.7.0/pkg/quicksort/quicksort.go (about)

     1  // Package quicksort implements Quicksort.
     2  package quicksort
     3  
     4  // Sort sorts the slice.
     5  func Sort(data []int) {
     6  	sort(data, 0, len(data)-1)
     7  }
     8  
     9  func sort(c []int, start, end int) {
    10  	if end <= start {
    11  		return
    12  	}
    13  	i, j := start, end+1
    14  	// ensure: c[start] <= c[start+1] <= c[end]
    15  	if c[start] > c[end] {
    16  		c[start], c[end] = c[end], c[start]
    17  	}
    18  	if c[start+1] > c[end] {
    19  		c[start+1], c[end] = c[end], c[start+1]
    20  	}
    21  	if c[start] > c[start+1] {
    22  		c[start], c[start+1] = c[start+1], c[start]
    23  	}
    24  	comp := c[start]
    25  	for {
    26  		for ok := true; ok; ok = c[i] < comp {
    27  			i++
    28  		}
    29  		for ok := true; ok; ok = c[j] > comp {
    30  			j--
    31  		}
    32  		if j <= i {
    33  			break
    34  		}
    35  		c[i], c[j] = c[j], c[i]
    36  	}
    37  	c[start], c[j] = c[j], c[start]
    38  	sort(c, start, j-1)
    39  	sort(c, j+1, end)
    40  }